Search code examples
cmemoryfree

C - pointer being freed was not allocated


I am trying to free a pointer that I assigned from a vector allocated with malloc(), when I try to remove the first element(index [0]), it works, when I try to remove the second(index [1]) I receive this error:

malloc: *** error for object 0x100200218: pointer being freed was not allocated

The code:

table->t = malloc (sizeof (entry) * tam);
entry * elem = &table->t[1];
free(elem);

Solution

  • You can only call (or need to) free() on the pointer returned by malloc() and family.

    Quoting C11, chapter §7.22.3.3

    [...] Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

    In your case, table->t (or, &table->t[0]) is that pointer, not &table->t[1].

    That said, free()-ing table->t frees the whole memory block, you don't need to (you can't, rather) free individually/ partially. See this answer for more info.