2013-03-27 58 views
0

下面的函數嘗試按升序對鏈表上的字符串進行排序。當它返回新的列表時,它將被損壞。strcpy損壞字符數組(字符串值)

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; 
    } 
} 

例如,如果輸入的是

piero 
ronaldo 
messi 

則輸出看起來像

messi 
ŽŽŽ 
ronaldo 

上面的例子不是在代碼嘗試,但它會給你一個線索。我相信有一些內存的分配,但我無法找到它。順便說一下,有時這些詞也是空的。

而且,單詞列表如下:

struct wordlist{ 
    char *word; 
    struct wordlist *next; 
}; 
+1

要訂購鏈接列表,您不需要執行所有這些內存分配,只要您想要移動某些東西,您應該只需更改一些「下一個」指針即可。在相關說明中,您將內存分配給'second',然後您立即使用'second = first-> next;' – lxop 2013-03-27 02:21:52

+1

您意識到您可以交換指針,對嗎?你不必'realloc'和'strcpy'來移動它們。 – paddy 2013-03-27 02:23:39

回答

1

你不圍繞複製字符串到您的臨時的第一次。

  if(temp->word == NULL){ 
       temp->word = malloc(sizeof(first->word)); 
       // You forgot to copy!! 
      } 
      else{ 
       if(realloc(temp->word, sizeof(first->word)) != NULL){ 
        strcpy(temp->word, first->word); 
       } 
      } 

看,如果temp->wordNULL,它應該是在第一時間(注意,你實際上並不明確temp結構已經這樣你會得到未定義的行爲),那你就不要複製它。快速解決辦法是在malloc之後執行strcpy。您的realloc電話都是錯誤的。您不能使用sizeof來獲取字符串的大小。爲此,請使用strlen,並且不要忘記爲字符串終止符添加一個額外的字節。

此外,您不應該分配firstsecond。它們是您數據結構的迭代器。你做的第一件事就是放棄它們的價值,以便泄漏記憶。之後請不要忘記free您的temp結構以及temp->word

當你得到那個工作後,請停止所有這mallocstrcpy業務!

要移動你周圍的字符串,只需要移動指針。不需要重新分配或複製。這將簡化您的代碼到少數幾行。

哦,你還忘了return從你的函數值?

+0

我剛剛刪除了「if strcmp {}」部分中的所有內容,並在三行中進行了指針交換。它像一個魅力。我浪費了幾個小時來解決這個問題,但它非常簡單。謝謝。 – gzg 2013-03-27 02:35:01

+1

沒問題。它沒有被浪費 - 希望你從經驗中學到很多東西=) – paddy 2013-03-27 02:37:09