0

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);
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Matheus Weber
  • 247
  • 1
  • 4
  • 13

3 Answers3

11

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.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
3

It works on the first element because &table->t[0] is equal to table->t. That's because the first element has the same address as the array itself (by definition of the array). And since the array itself has an address that has been allocated, only that one can be freed.

Bogdan Alexandru
  • 5,394
  • 6
  • 34
  • 54
1

malloc() works by allocating a single contiguous memory area, whose usable size is the single integer parameter passed by it. It returns a pointer for the allocated area.

You can only free the returned pointer once, and not a subset of it.

Arrays aren't objects in C, they're syntatic sugar to pointer arithmetic, which is probably the main headache of C programming and the area you should carefully study if you're committed to learning C.