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

时间:2014-11-02 08:29:09

标签: c string memory-management

我正在尝试创建一个继续将字符串附加到char变量的函数。但是,有时它会起作用,有时却不起作用。我想知道bug在哪里?

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

1 个答案:

答案 0 :(得分: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 );
}