In the code below, I'm attempting to concatenate 2 strings: str1 and str2 using strcat from string.h
Since the length of destination string, str1
is 6 bytes on the stack, I expect any store of a length more than 6 shall trigger the stack smashing detected
warning message.
However, I see that the message is triggered only in case where Im attempting to write 8 bytes (12345,67,NUL) which is what strcat
will do when called as strcat(str1, str2)
Surprisingly, a write of 7 bytes (12345,6,NUL) does NOT trigger the stack smashing detected
warning, this seems wrong. I realize that strcat
specifies undefined behavior when destination size is insufficient, but why does it affect the stash smashing check?
#include <stdio.h>
#include <string.h>
int main() {
char str1[6] = "12345";
char* str2 = "6"; // works fine, but why?
//char* str2 = "67"; // gives "*** stack smashing detected ***: terminated"
strcat(str1, str2);
return 0;
}
gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0