0

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

Electrix
  • 510
  • 3
  • 14
  • If you drive off the road and crash into a small tree in an undeveloped part of town, you may get away with it. But if you crash into the side of a rich guy's mansion, there may be more severe consequences. – Steve Summit Oct 08 '22 at 02:11
  • This is not a question that can be answered at the C level. Post the assembly. We need to know all the choices that your compiler made here. – Siguza Oct 08 '22 at 02:25
  • There is no way in 'c' to detect stack corruption. There are some mechanisms which can help detecting it in some cases and they are not precise and do not necessarily work. So, question about correctness of the such a checker does not make sense. – Serge Oct 08 '22 at 03:02

0 Answers0