Reputation: 283
#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?
Upvotes: 0
Views: 600
Reputation: 21213
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.
Upvotes: 0
Reputation: 108
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.
Upvotes: 0
Reputation: 36362
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.
Upvotes: 2