void StrcatStr(char *s, char *t) {
while (*s != '\0');
while ((*s = *t ) != '\0');
}
int main() {
char str1[] = "abcd";
char str2[] = "sss";
StrcatStr(str1, str2);
printf("%s", str1);
return 0;
}
At first, I found pointer s
point to the character 'a'
, but next it pointed invalid character in string. Finally, system told me stack around the variable str1
was corrupted. Why did this thing happen? Shouldn't the pointer s
point to the character 'b'
next?
CodePudding user response:
The definition
char str1[] = "abcd";
is equivalent to
char str1[5] = { 'a', 'b', 'c', 'd', '\0' };
That means the array will have only five elements. And arrays are not dynamic and can't be extended after their definition.
So using this as a destination for any strcat
-like function will write out of bounds and give you undefined behavior.
You need to make sure that the array have enough space in it to fit both strings, for example by setting an explicit size (that is known to be enough):
// 30 should be more than enough to fit two 4-character strings plus the terminator
char str1[30] = "abcd";
CodePudding user response:
The problem here is the first while, you should write *( s) instead of *s . With s you're actually giving in return the current value of s and then incrementing is value, what happens when you get to '\0'? s -> '\0', the condition in the while loop is now false, but you're still incrementing the value!! So you're not pointing to the '\0' character, but to 1 char ahead of it. With you're second while you modify bytes out of the string, and considering there's still the '\0', printf doesn't show the second string. With ( s) you increment first and return the new value so you can stop at the end of the first string ,pay attention when you're first string has no characters you should deal with it in a separate case.