free()后出现段错误,常见原因是什么?
在释放
某个指针后,我遇到了分段错误:
free(studentDB->name);
我可以在没有任何错误或警告的情况下获取它的值:
printf("[DBG] studentDB->name: %s\n", studentDB->name);
但是,正如我所说,当我尝试释放它时,程序崩溃了。 free
命令导致分段错误的最常见原因是什么?
I get a segmentation fault after free
ing a certain pointer:
free(studentDB->name);
I can get its value without any errors or warnings:
printf("[DBG] studentDB->name: %s\n", studentDB->name);
However, as I said, the program crashes when I try to free it. What are the most common causes for a free
command leading to a segmentation fault?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果您没有
malloc()
它,则无法free()
它。studentDB->name
从哪里来?If you didn't
malloc()
it, you can'tfree()
it. Where doesstudentDB->name
come from?您可能已经对其进行了 free() 编辑,或者覆盖了缓冲区溢出块之前的 malloc 信息
You've probably either free()'ed it already, or overwritten the malloc info preceding the block with a buffer overrun
通常在程序的其他地方会出现堆损坏。堆通常是连续的,堆管理器用标头包围堆块以跟踪块 - 如果您覆盖块的标头,则访问它是可以的,但 free 很可能会失败。
Usually heap corruption somewhere else in the program. The heap is usually continous and the heap manager surrounds heap blocks with headers to track the blocks- If you overwrite the header of the block, access to it is fine, but
free
is most likely to fail.如果studentDB 为NULL,则访问studentDB 指针的name 成员也可能会出现段错误。
Could also be that accessing the name member of the studentDB pointer is a segfault if studentDB is NULL.
free
的段错误可能是由于在未使用malloc
分配或已被free
分配的指针上调用它而引起的。如果您发布了分配
studentDB->name
的代码,将会有所帮助。A segfault from
free
can be caused by calling it on a pointer that was not allocated withmalloc
, or had beenfree
'd already.It would help if you posted the code where
studentDB->name
was allocated.studentDB->name
之前是否已分配?如果您没有为该字段分配内存,那么当您调用free
时,很可能会出现段错误!请检查该字段并确保它已被malloc
d 或strdup
d。或者堆上其他地方存在损坏,与此同时发生,因为您正确地指出您可以看到
name
的值...希望这有帮助,
此致,
汤姆.
Has
studentDB->name
being allocated previously? If you did not allocate memory for that field, chances are when you calledfree
, you end up with a seg-fault! Please check on that field and make sure it has beingmalloc
d orstrdup
d.Or that there is a corruption elsewhere on the heap, that coincided with this as you rightly pointed out you can see the value of
name
...Hope this helps,
Best regards,
Tom.
来自联机帮助页:
还可以检查:
From manpage:
One can also check: