Tuesday, 5 July 2016

c strcat overwrite source string?



I'm a Java programmer struggling to pick up C. In particular, I am struggling to understand strcat(). If I call:




strcat(dst, src);


I get that strcat() will modify my dst String. But shouldn't it leave the src String alone? Consider the below code:



#include
#include

void printStuff(char* a, char* b){

printf("----------------------------------------------\n");
printf("src: (%d chars)\t\"%s\"\n",strlen(a),a);
printf("dst: (%d chars)\t\"%s\"\n",strlen(b),b);
printf("----------------------------------------------\n");
}

int main()
{
char src[25], dst[25];
strcpy(src, "This is source123");

strcpy(dst, "This is destination");

printStuff(src, dst);
strcat(dst, src);
printStuff(src, dst);

return 0;
}



Which produces this output on my Linux box, compiling with GCC:



----------------------------------------------
src: (17 chars) "This is source123"
dst: (19 chars) "This is destination"
----------------------------------------------
----------------------------------------------
src: (4 chars) "e123"
dst: (36 chars) "This is destinationThis is source123"
----------------------------------------------



I'm assuming that the full "This is source123" String is still in memory and strcat() has advanced the char* src pointer forward 13 chars. But why? Why 13 chars? I've played around with the length of the dst string, and it definitely has an impact on the src pointer after strcat() is done. But I don't understand why...



Also... how would you debug this, in GDB, say? I tried "step" to step into the strcat() function, but I guess that function wasn't analyzed by the debugger; "step" did nothing.



Thanks!
-ROA



PS - One quick note, I did read through similar strcat() posts on this site, but didn't see one that seemed to directly apply to my question. Apologies if I missed the post which did.



Answer



Your destination doesn't have enough memory allocated to hold the new concatenated string. In this case this means that src is probably being overwritten by strcat due to it writing beyond the bounds of dst.



Allocate enough memory for dst and it should work without it overwriting the source string.
Note that the new memory segment that holds the concatenated strings needs to be at least the size of the two strings(in your case 36) plus space for the null terminator.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...