Releasing a pointer after pointer arithmetic

My question is very simple. Say we have:

char* ptr = (char*) malloc(sizeof(char)*SIZE); ptr+= SIZE/2; free(ptr); 

What happens when we free a pointer? Is this an undefined operation? Does it free the entire SIZE buffer or just the remaining SIZE / 2? Thanks in advance for resolving this issue for me.

+4
source share
5 answers

Your program is likely to crash: the free () operation is actually quite simple in C, but only works with the original allocated address.

A typical memory allocator works like this pseudo-code:

  • ask for 64 bytes
  • the allocator allocates 70 bytes (another 6 bytes)
  • the first 2 bytes are set to "signature", a pattern recognized by the allocator to identify the memory allocated to it
  • the next 4 bytes indicate the allocated size
  • returns a pointer to the beginning of the 7th byte

Therefore, when you call free(ptr) , the allocator sends 6 bytes in front of the pointer to verify the signature. If he does not find the signature, he crashes :)

+9
source

If the free() argument does not match the pointer previously allocated with malloc() and friends, the behavior is undefined. Most likely, you will encounter a segmentation error or a failed statement in your version of libc .

Offtopic: it's best not to pronounce the result of malloc() in C.

+8
source

The behavior is undefined and is likely to lead to a segmentation error - and that is a good case . In the worst case scenario, it will damage your program memory and cause all kinds of strange errors and incorrect outputs.

+2
source

In most implementations, this should lead to some kind of fatal error. You can free only the beginning of the allocated buffer.

The typical error you might get in windows (using visual studio compilers) would be something like an "invalid heap pointer". On linux, as phihag said above, this usually results in a segmentation error. In both cases, this is a run-time error that usually interrupts program execution.

+2
source

The behavior is undefined. I think you will get segfault ... this is what I got when I tried on my system.

free() requires the caller to pass an address that was returned by a memory allocation function, such as malloc() . Everything else leads to undefined behavior.

+2
source

All Articles