#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main() {
char *a = "aaaaaaaaaaaaaaaa";
char b[1];
strcpy(b, a);
printf("%s\n", b);
}
When running, it prints:
aaaaaaaaaaaaaaaa
If I make *a super long, for example, *a="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", then it will cause a segfault.
Why there is no overflow in the first case?
A segmentation fault happens when your program tries to access memory that doesn't belong to your program's virtual address space; this will not happen if you just overwrite a bit of stuff right after your original copy destination.
There is buffer overflow, it doesn't mean it will always couse segmentation fault. It is undefined behaviour - there MAY be segfault. It depends on what is "placed" right after your variable in memory.
Appearing to work, or, for that matter, not crashing, is a valid form of undefined behavior. Anything can happen when your program has UB. That's why it's highly undesirable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.