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?
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.