Ok, so I'm screwing around with C trying to break stuff in a somewhat safe manner, like calling malloc(100000000000000)
and having my computer run out of memory for a microsecond, and I thought, what would happen if I tried to put too much info in a variable, so I did this...
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
int *p;
p = malloc(1);
*p = 100;
printf("%d", *p);
free(p);
printf("%d", *p);
printf("Hello, World!\n");
return 0;
}
This does two things I didn't expect.
- First, it prints
p
twice. I thoughp
would "vanish" after I freed it. (Though on second thought, I may have to let the OS run a while before it vanished.) - Second, I expected it to crash. I'm putting 100, a 4 byte int in a box that I think is supposed to be 1 byte. Does
malloc(1)
malloc one byte? Or is it more likemalloc(sizeof(int))
? Why does this work? And, assuming the compiler would let me, how would I cause the buffer overflow (is that the right name here?) that I'm trying to cause?
Pertinent computer info:
- OS: Mac OS X 10.10.latest
- compiler: Xcode, so clang/llvm