What is wrong with the function. How come nothing gets printed out?
char * CombineStr(char * str1, char * str2)
{
char strOut[256];
sprintf(strOut, “%s%s”, str1, str2);
return strOut;
}
What is wrong with the function. How come nothing gets printed out?
char * CombineStr(char * str1, char * str2)
{
char strOut[256];
sprintf(strOut, “%s%s”, str1, str2);
return strOut;
}
You should take care of scope (storage duration of your variable): either declare returned variable as static, or allocate it dynamically on the heap, using malloc
, and free
ing the allocated memory pointed to by strOut
, once not needed anymore. You should use plain quotes in the format of your sprintf
second argument. You should take care against overflow.
either:
char * CombineStr(char * str1, char * str2)
{
static char strOut[256]; //scope!
if((strlen(str1) + strlen(str2)) < 256)
sprintf(strOut, "%s%s", str1, str2); //plain quotes!
return strOut;
}
or:
char * CombineStr(char * str1, char * str2)
{
char strOut = malloc(strlen(str1) + strlen(str2) + 1);
if( strOut != NULL )
sprintf(strOut, "%s%s", str1, str2); //plain quotes!
return strOut;
}
For further reading, please take a look at following SO posts: 1, 2.
Another common solution is to have the caller provide the output buffer
char * CombineStr(const char * str1,
const char * str2,
char * strOut,
size_t outlen)
{
size_t len = snprintf(strOut, outlen, "%s%s", str1, str2);
if (len < outlen)
{
return strOut;
}
return NULL;
}
Note the switch from sprintf
to snprintf
to prevent buffer overflow should the concatenated string exceed the length of the buffer. This allows us to catch the overflow and return an invalid result to let the caller know buffer
cannot be trusted.
Typical usage would be
char buffer[256];
if (CombineStr("I's the b'y that builds the boat",
"And I's the b'y that sails her",
buffer,
sizeof(buffer)) != NULL)
{
// use buffer
}
It needs to be noted that snprintf
has wonky support and cannot always be trusted to have been null terminated, but you can be sure that it didn't overflow the buffer.
Change to static char strOut[256];
. It is not very good solution but will work.