I’m toying with buffer overflows, but I’m confused by what I’m finding when running the following simple C program on Mac OS.
#include <stdio.h>
int main(void) {
char buf[2];
scanf("%s", buf);
printf("%s\n", buf);
}
By setting the length of buf to 2 bytes, I expected to cause a segmentation fault when entering the string “CCC”, but that doesn’t happen. Only when entering a string 24 characters in length do I incur a segmentation fault.
What’s going on? Is it something to do with character encoding?
Thanks.
The behavior of your program is undefined as soon as you overflow the buffer. Anything can happen. You can’t predict it.
There might or might not be some padding bytes after your buffer that happen to be unimportant to your code execution. You can’t rely on that. A different compiler, compiling in 32bit vs 64bit, debug settings… all that could alter your code execution after that overflow.