C - pointer being freed was not allocated

蹲街弑〆低调 提交于 2020-01-06 20:29:06

问题


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

回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/36649624/c-pointer-being-freed-was-not-allocated

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!