I have written following program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main(int argc, char *argv[]){
char *input;
input = (char*)malloc(16);
printf("input is : %s\n", input);
}
When I run this as:
./test `python -c 'print "A"*5000'`
it does not crash. It rather prints data.
When I use free(input)
after printf
, it crashes.
Why does this happen?
The code shown ignores its command line arguments:
It shouldn't matter what the Python script provides. However, your
printf()
is printing uninitialized data; that leads to undefined behaviour. If theprintf()
doesn't crash and there is afree(input);
call after theprintf()
, then thefree()
shouldn't crash.If you missed out a copy operation and intended to show something like this, then the rules are different:
Now you are not checking that
argv[1]
is not a null pointer before you use it — that could cause a crash. And you are trampling way out of bounds of the allocated memory if you pass 5000 characters inargv[1]
. Something will probably trigger a crash; it isn't defined what will cause the crash. Thestrcpy()
may fail; theprintf()
probably won't fail if the copy doesn't (but that isn't guaranteed); thefree()
will probably fail because you trampled out of bounds (but even that isn't guaranteed). Such are the wonders of 'undefined behaviour'; anything could happen and it is valid behaviour.Buffer overflow (in this case heap overflow) doesn't cause immediately crash. Writing outside of bounds of allocated memory causes undefined behavior - anything might happen; even it can work correctly.
If you don't even initialize pointer
input
and dereference it (read or write there), most likely you will get a SEGFAULT, but it's still 'only' undefined behavior.From C99 draft standard
But be be careful
An overflow may result in data corruption or unexpected behavior by any process which uses the affected memory area. On operating systems without memory protection, this could be any process on the system.