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

Or Cyngiser picture Or Cyngiser · Sep 17, 2013 · Viewed 45.7k times · Source

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

Answer

Tim picture Tim · Sep 17, 2013

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.