Reputation: 268
From what I've read and understand, for example when we pass a string to a function, inside that function we can't use sizeof( array )/sizeof( array[ 0 ] ) to determine the length of the string. So I was wondering it this function to append a character to the end of a string is correct:
void append_ch_to_str( char *str, char ch )
{
int length = strlen( str );
str = ( char * )realloc( str, ( length + 1 ) * sizeof( char ) );
length = strlen( str );
*( str + length - 1 ) = '\0';
*( str + length - 2 ) = ch;
}
Upvotes: 2
Views: 1460
Reputation: 1438
It is not correct, but may be corrected as follows:
char *append_ch_to_str( char *str, char ch )
{
int length = strlen( str );
char *str2;
str2 = ( char * )realloc( str, ( length + 2 ) * sizeof( char ) );
if (!str2) {
free(str);
return NULL;
}
str = str2;
str[length] = ch;
str[length+1] = 0;
return str;
}
All this is assuming that the str
pointer is to already allocated memory with malloc/calloc/strdup
.
Allocation should provide space for terminating 0
character and one more for the added one.
The second calculation of string length will have the same result, because it will count characters that are non-zero, and will not return the size of the allocated buffer.
You have to check for realloc returning NULL
in case of not enough memory. EDIT: I added checking for realloc return value - this will hopefuly prevent copying the unfinished code...
As pointed in comments this is also a bad approach because realloc is not guaranteed to return the same pointer value, that is why the function will return the new pointer value and the original one will no longer be valid after its execution.
Upvotes: 2
Reputation: 59997
You are going to have a memory leak as realloc
may return a different pointer that str, which that you throw awary.
Also due to this the new string is not passed back to the caller.
Upvotes: 1