简体   繁体   中英

Function to append a character to the end of a string

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM