gpt4 book ai didi

C - 附加到字符串 - 可能的内存错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:46:29 25 4
gpt4 key购买 nike

我正在尝试创建一个函数,该函数不断将字符串附加到 char 变量。但是,有时它有效,有时则无效。我想知道错误在哪里?

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

最佳答案

问题出在函数 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 );
}

关于C - 附加到字符串 - 可能的内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26697435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com