Tuesday, 15 September 2015

c - strcpy corrupts char array (string value) -


The function below tries to order in ascending order on a linked list. When it gives a new list, it gets corrupted.

  Zero * command (zero * ptr) {struct wordlist * head; Head = (Straight word list *) PTR; StructureWorldList * first = (Straight wordlist) * Molec (Psychof (Straight Waldlist)); Structure terminology * second = (structure wordlist *) malloc (sarcasm (structure wordlist)); Struct wordlist * temp = (Structure word list *) malloc (form (word structure)); First = head; Int j = 1; While (first! = Null) {seconds = first-> next; While (second! = Null) {if (SRCMP (first-> word, seconds-> words)> {if (temp-> word == NULL) {temp-> Word = malloc (sizeof (first> terms)); } And {if (realloc (temp-> word, size (first- & gt; word)) = null) {strcpy (temp-> word, first-> word); }} If (realloc (first-> word, size (second-> word)) = tap) {strcpy (first-> words, second-> words); } If (realloc (second-> word, size (temp-> words)! = Null) {strcpy (second-> words, temp-> terms); } Free (temp); } Second = second->; next; } J ++; First = first->; next; For example, if input will be  
  piero ronaldo messi   

then the output looks <

given above The example code is not tried on the code, but it will give you a clue. I believe there is something with the allocation of memory but I could not find it. By the way, sometimes the words are also empty.

In addition, the word list is as follows:

  struct word list {char * word; Structure word list * next; };    

You do not temporarily copy the string for the first time.

  if (temp-> words == faucet) {temp-> Word = malloc (sizeof (first-> word)); // You forgot to copy !! } And {if (realloc (temp-> word, size (first- & gt; word)) = null) {strcpy (temp-> word, first-> word); }}   

See if temp-> The word is is NULL , which should be for the first time (note that you do not actually specify temp struct, So you will get an undefined behavior already), you will not copy it, after you malloc you have to make the quick code strcpy .

Your realloc calls are all incorrect You can not use the sizeof to get the size of the string. Use strlen for this, and do not forget to add an extra byte to string terminator.

In addition, you must first and second . They are fast for your data structure. The first thing that you do is discard your value so that you can leak your memory free with your temp structure as well as temp-> Do not forget the word later.

After you receive it, it is working, please stop all this malloc and strcpy business!

To move the stars around you, only the signals need to be transferred. Necessary rearrangement or copies will not simplify your code in a handful of lines.

Oh, and did you forget the return value from your work?

No comments:

Post a Comment