steve
steve

Reputation: 21

C question on free()

#include <stdio.h>
int main ()

{

   int *p = (int *)malloc((100*sizeof(int)));

   p++;

   free(p);

/* do something */

return 0;

}

Questions:

  1. Will the memory starting from the location p+1 be free(say if malloc returned 0x1000, the memory freed will be from 0x1004,assuming a 4 byte integer)?

  2. Are there anypitfalls of this code apart from the fact that the 4 bytes from 0x1000(if malloc returned 0x1000) are not useable (unless you do a p-- and use the address)

Upvotes: 2

Views: 218

Answers (5)

Aviad Rozenhek
Aviad Rozenhek

Reputation: 2429

in standardese this behavior is "undefined", but actually, nothing will get freed. the reason is that what malloc does it keep a list of the chunks it had allocated, each chunk is identified by its starting address. p+1 is not on that list, so free will find a chunk to free, and will do nothing.

Upvotes: 0

codeomnitrix
codeomnitrix

Reputation: 4249

Hey I tried this code over gcc and it stopped with:

*** glibc detected *** ./a.out: free(): invalid pointer: 0x0829600c ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6(+0x6b591)[0x7be591]
/lib/tls/i686/cmov/libc.so.6(+0x6cde8)[0x7bfde8]
/lib/tls/i686/cmov/libc.so.6(cfree+0x6d)[0x7c2ecd]

So as per your first answer you can't free the next memory location. and for the second question: and the four bytes won't be usable unless you do p-- and this code will work fine unless you change the contents of next memory location and you can use the allocated memory location by doing p--

Upvotes: 0

ChrisJ
ChrisJ

Reputation: 5261

The free() call will fail, because p is no longer the address of a block allocated with malloc().

Upvotes: 1

sharptooth
sharptooth

Reputation: 170549

That's undefined behavior - you must pass exactly the same pointer to free() as you obtained from malloc(). With your code anything can happen - likely heap will be corrupted.

Think of it this way. free() has only one parameter, so it must deduce what to mark free from exactly that one parameter. There's no way to "free less memory" - either it will free all (deduction required for that will be very time-consuming btw), or something bad happens - the latter is more likely. You shouldn't assume anything, just don't do that.

Upvotes: 12

Marek Sapota
Marek Sapota

Reputation: 20608

This code just won't work - you can only free pointers that were allocated by malloc or similar function, you can't free part of the allocated memory range.

Upvotes: 0

Related Questions