Reputation: 651
I am trying to a create a function that keeps on appending a string to a char variable. However, some times it works and other times it doesn't. I am wondering where the bug is?
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));
}
Upvotes: 1
Views: 62
Reputation: 311058
The problem is in function add_string
. You do not append the allocated or copied array with the terminating zero after statements
final_output = malloc(strlen(text) + 1);
and
strncat(final_output, text, strlen(text));
Rewrite the function the following way
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 );
}
Upvotes: 2