The function below tries to order strings on a linked list in ascending order. When it returns the new list, it becomes corrupted.
void* order( void *ptr){
struct wordlist *head;
head = (struct wordlist *) ptr;
struct wordlist *first = (struct wordlist*)malloc(sizeof(struct wordlist));
struct wordlist *second = (struct wordlist*)malloc(sizeof(struct wordlist));
struct wordlist *temp = (struct wordlist*)malloc(sizeof(struct wordlist));
first = head;
int j = 1;
while( first != NULL){
second = first->next;
while( second != NULL){
if( strcmp( first->word, second->word) > 0){
if( temp->word == NULL){
temp->word = malloc( sizeof(first->word));
}
else{
if( realloc( temp->word, sizeof( first->word)) != NULL){
strcpy( temp->word, first->word);
}
}
if( realloc( first->word, sizeof(second->word)) != NULL){
strcpy( first->word, second->word);
}
if( realloc( second->word, sizeof(temp->word)) != NULL){
strcpy( second->word, temp->word);
}
free(temp);
}
second = second->next;
}
j++;
first = first->next;
}
}
For example, if input would be
piero
ronaldo
messi
then the output looks like
messi
ŽŽŽ
ronaldo
The above example is not tried on the code, but it will give you a clue. I believe there is something with the allocation of the memory but I could not manage to find it. By the way, sometimes the words come empty too.
Also, the wordlist is as follows:
struct wordlist{
char *word;
struct wordlist *next;
};