-1

I'm initializing a void pointer with 1 byte of memory and typecasting it to a int pointer and dereferencing it giving it a value 3(which needs 4 bytes) but it is running fine. Shouldn't this result in an error or cause a runtime exception like OOM?

void* record = malloc(1);
int i=3;
*((int*)record) = 3;
Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
HarshaNadimpalli
  • 534
  • 4
  • 12
  • When you misuse pointers like this, it's *undefined behavior*. It's allowed to do anything: work or not, crash or not, give you a compiler warning or not, etc. – Steve Summit Oct 07 '17 at 03:48
  • "Shouldn't this ideally cause an exception?" that would be _defined behavior_. Why define how a language must fail? – chux - Reinstate Monica Oct 07 '17 at 03:50
  • 1
    The nasty fact here is that, undefined or not, it'll actually work on most C++ implementations because nearly all heaps actually allocate in units of either machine words or some small multiple of machine words. I.e., you'll find your heap actually allocated 4 or 8 or 12 or even 16 bytes for your `malloc(1)` call. (The exceptions would be those heaps, very rare, which keep heap metadata separate from allocated memory or which have special treatment for allocations of less than one machine word.) The reason why it's nasty is that it'll nearly always work. Until, one day, it doesn't. – davidbak Oct 07 '17 at 04:29
  • P.S. I said C++ implementations, but, also C. – davidbak Oct 07 '17 at 04:36

1 Answers1

5

When you write past the end of a memory block allocated by malloc as you've done here, you invoke undefined behavior.

Undefined behavior means the behavior of the program can't be predicted. It could crash, it could output strange results, or it could appear to work properly. Also, a seemingly unrelated change such as adding an unused local variable or a call to printf for debugging can change the way undefined behavior manifests itself.

To summarize, with undefined behavior, just because the program could crash doesn't mean it will.

dbush
  • 205,898
  • 23
  • 218
  • 273