我想創建一個函數,它將一個字符串附加到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));
}
這是多餘的使用'strncat函數() '當長度爲'strlen(text)'時,'因爲'strcat()'不需要讀取字符串兩次。 – Barmar 2014-11-02 08:31:17
+2同樣是多餘的。你只需要+1作爲唯一的終止符,結果字符串將被放置。我希望你意識到,只要你走到輸出循環中的終止符,你就失去了唯一的指向字符串的指針。 (嗨,你打算如何解放那件事?)。最後,停止在C中分配賦值函數。[沒有什麼好的辦法](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 – WhozCraig 2014-11-02 08:32:40
它不起作用時會發生什麼?我無法讓它失敗。 – Barmar 2014-11-02 08:34:54