C-释放的指针未分配 [英] C - pointer being freed was not allocated
问题描述
我试图从分配给malloc()
的向量中释放分配给我的指针,当我尝试删除第一个元素(索引[0])时,当我尝试删除第二个元素(索引[ 1])我收到此错误:
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
代码:
table->t = malloc (sizeof (entry) * tam);
entry * elem = &table->t[1];
free(elem);
推荐答案
您只能在(或需要)free()
调用由malloc()
和family返回的指针.
You can only call (or need to) free()
on the pointer returned by malloc()
and family.
引用C11
,第7.22.3.3章
Quoting C11
, chapter §7.22.3.3
[...]否则,如果 该参数与内存管理器先前返回的指针不匹配 函数,或者如果通过调用
free
或realloc
释放了空间,则 行为是不确定的.
[...] 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
orrealloc
, the behavior is undefined.
在您的情况下,table->t
(或&table->t[0]
)是该指针,而不是&table->t[1]
.
In your case, table->t
(or, &table->t[0]
) is that pointer, not &table->t[1]
.
也就是说,free()
-ing table->t
会释放整个内存块,您不需要(也不能)单独/部分释放.有关更多信息,请参见此答案.
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.
这篇关于C-释放的指针未分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!