Sathish
Sathish

Reputation: 237

Free causes a error : free(): invalid pointer: 0x0000000001d04018

I tried to compile the following code :

#include <stdio.h>

void main()
{
    int *p = (int*) malloc(4*sizeof(int));
    p++;
    p++;
    free(p);
}

But it gives me the following error.

* Error in `/home/a.out': free(): invalid pointer: 0x0000000001d04018 *
Aborted.

I think I am still within the allocated limits of size 4 ints. But then why invalid pointer. Can some one help.

Upvotes: 0

Views: 2273

Answers (3)

taskinoor
taskinoor

Reputation: 46027

You are invoking undefined behavior.

From free manual:

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs.

It doesn't matter whether you are inside allocated region or not. The pointer must be the same that was allocated before.

The rationale for being it undefined is that typical implementation (this is implementation defined) must remember other metadata related to the allocation, e.g. the allocation size, in some data structure in order to free them later. If ptr is not same as returned by allocation function then there is no way to lookup into this data structure to get those metadata during freeing.

Upvotes: 4

tadman
tadman

Reputation: 211560

The free() function can only operate on a pointer that has been directly allocated with malloc() or any of its companions.

If you change the pointer you'll have errors like this, that modified pointer was never allocated.

"Close enough" does not count. It must be identical to the pointer you got in the first place.

Upvotes: 2

The contract for malloc and free is fairly simple. The pointer value (the address) you pass to free must be exactly a pointer value you got from malloc.

Exactly, and not in the same block, however close. It must match exactly. You modify the pointer before passing it back (you increment), so you violate that contract. This is going to cause undefined behavior. And you experience it in the from of a crash. It could be worse, it could appear to work. Until it blows up in your face later for no apparent reasons. That's the nature of undefined behavior. Avoid it.

Upvotes: 1

Related Questions