Home > OS >  The use of strcat in C overwrites irrelevant strings
The use of strcat in C overwrites irrelevant strings

Time:12-11

The code is as follows:

char seg1[] = "abcdefgh";
char seg2[] = "ijklmnop";
char seg3[] = "qrstuvwx";

strcat(seg2, seg3);

Then the value stored in seg1 will become:

"rstuvwx\0\0"

I have learned to declare that strings with close positions are also adjacent in the stack area, but I forgot the details.

I guess the memory address of seg1 was overwritten when strcat() was executed, but I'm not sure about the specific process. Can someone tell me the specific process of this event?Thanks

CodePudding user response:

C does not have a string class, it has character arrays which may be used as strings by appending a null terminator. And since there is no string class, all memory management of strings/arrays must be done manually.

char seg1[] = "abcdefgh"; Allocates space for exactly 8 characters and 1 null terminator. There is no room to append anything else at the end. If you try anyway, that's the realm of undefined behavior, where anything can happen. Crashes, overwriting other variables, program ceasing to function as expected and so on.

Solve this by allocating enough space to append something in the end, for example
char seg1[50] = "abcdefgh";. Alternatively allocate a new, third array and copy the strings into that one.

  • Related