Why does not a segmentation error occur when strcpy () causes a buffer overflow?

#include <stdio.h> #include <stdlib.h> #include <string.h> void main() { char *a = "aaaaaaaaaaaaaaaa"; char b[1]; strcpy(b, a); printf("%s\n", b); } 

At startup, it prints:

 aaaaaaaaaaaaaaaa 

If I make * super long, for example * a = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", then this will cause segfault.

Why in the first case there is no overflow?

-1
source share
3 answers

A segmentation error occurs when your program tries to access memory that does not belong to the virtual address space of your program; this will not happen if you just overwrite a few things right after your original destination.

+2
source

There is a buffer overflow, this does not mean that it will always have a segmentation error. This behavior is undefined - MAY be segfault. It depends on what is "placed" immediately after your variable in memory.

0
source

The appearance of work, or for that matter, not failure, is a valid form of undefined behavior. Anything can happen when your program has UB. Therefore, it is very undesirable.

0
source

Source: https://habr.com/ru/post/985281/


All Articles