Search code examples
cc-strings

Why do I first have to strcpy() before strcat()?


Why does this code produce runtime issues:

char stuff[100];
strcat(stuff,"hi ");
strcat(stuff,"there");

but this doesn't?

char stuff[100];
strcpy(stuff,"hi ");
strcat(stuff,"there");

Solution

  • strcat will look for the null-terminator, interpret that as the end of the string, and append the new text there, overwriting the null-terminator in the process, and writing a new null-terminator at the end of the concatenation.

    char stuff[100];  // 'stuff' is uninitialized
    

    Where is the null terminator? stuff is uninitialized, so it might start with NUL, or it might not have NUL anywhere within it.

    In C++, you can do this:

    char stuff[100] = {};  // 'stuff' is initialized to all zeroes
    

    Now you can do strcat, because the first character of 'stuff' is the null-terminator, so it will append to the right place.

    In C, you still need to initialize 'stuff', which can be done a couple of ways:

    char stuff[100]; // not initialized
    stuff[0] = '\0'; // first character is now the null terminator,
                     // so 'stuff' is effectively ""
    strcpy(stuff, "hi ");  // this initializes 'stuff' if it's not already.