2014-11-02 18 views
1

我想創建一個函數,它將一個字符串附加到char變量上。然而,有些時候它有效,而有些時候則不適用。我想知道錯誤在哪裏?C - 追加到字符串 - 可能的內存錯誤

char *final_output = NULL; 
void add_string(const char *); 

int main(void) { 
    add_string("Hello world\n"); 
    add_string("This is my new function!\n"); 

    /* Let's print */ 
    while (final_output && *final_output) { 
     printf("%c", *final_output); 
     *final_output++; 
    } 
} 

void add_string(const char *text) { 
    if (final_output == NULL) { 
     final_output = malloc(strlen(text) + 1); 
    } 
    else { 
     final_output = (char *) realloc(final_output, strlen(final_output) + strlen(text) + 2); 
    } 

    strncat(final_output, text, strlen(text)); 
} 
+2

這是多餘的使用'strncat函數() '當長度爲'strlen(text)'時,'因爲'strcat()'不需要讀取字符串兩次。 – Barmar 2014-11-02 08:31:17

+2

+2同樣是多餘的。你只需要+1作爲唯一的終止符,結果字符串將被放置。我希望你意識到,只要你走到輸出循環中的終止符,你就失去了唯一的指向字符串的指針。 (嗨,你打算如何解放那件事?)。最後,停止在C中分配賦值函數。[沒有什麼好的辦法](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 – WhozCraig 2014-11-02 08:32:40

+0

它不起作用時會發生什麼?我無法讓它失敗。 – Barmar 2014-11-02 08:34:54

回答

2

問題出在功能add_string。你不分配或複製的數組與終止零追加陳述後

final_output = malloc(strlen(text) + 1); 

strncat(final_output, text, strlen(text)); 

重寫功能通過以下方式

void add_string(const char *s) 
{ 
    if (final_output == NULL) 
    { 
     final_output = malloc(strlen(s) + 1); 
     final_output[0] = '\0'; 
    } 
    else 
    { 
     final_output = realloc(final_output, strlen(final_output) + strlen(s) + 1); 
    } 

    strcat(final_output, s); 
} 
+0

美麗的哥們!解決我所有的問題!非常感謝!! – antikbd 2014-11-02 08:45:35

+0

@ antikbd不客氣。 – 2014-11-02 08:50:54

+0

Vlad,我還有一個問題:假設我有一個名爲int i = 123的變量。如果我想直接傳遞這個i,像add_string(i),我應該怎麼做?謝謝! – antikbd 2014-11-02 09:16:31