简体   繁体   中英

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);

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM