0

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 though p 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 like malloc(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
Jonathan
  • 539
  • 4
  • 15
  • I think in both cases it is invoking undefined behaviour. – Sreeraj Chundayil May 04 '15 at 02:16
  • 2
    This will certainly cause you to overwrite 3 bytes of memory that doesn't belong to you. Then, after calling `free` you try and access 4 bytes of memory that don't belong to you. Any of those of those, by itself, will cause you to venture into the realm of undefined behavior. However there's no _requirement_ that the system crash in response. – Nik Bougalis May 04 '15 at 02:16
  • [Here](http://stackoverflow.com/questions/29979965/which-stream-does-stack-smashing-detected-message-get-printed-to) is an example of a buffer overflow, if you wanted that. – merlin2011 May 04 '15 at 02:18
  • Cool, thanks guys. I see this is a duplicate question, but hey I've learned something. I'll have to try that buffer overflow you linked to @merlin2011. I'm totally new to this stuff. :) – Jonathan May 04 '15 at 02:22
  • There's nothing bad about a question being marked a duplicate. Your question has become one more useful pointer to someone looking for the same information. – merlin2011 May 04 '15 at 02:24
  • Good to know. :) I just ran that buffer overflow code you linked to. The Xcode debugger shows that the OS didn't even try to fit "Hello, World" into the message. It only gets to "W". :) – Jonathan May 04 '15 at 02:27

0 Answers0