我有一个非常简单的测试程序,在Solaris上运行的5.8:当通常调用free()时,为什么会出现总线错误或分段错误?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *paths;
paths = getenv("PATH");
printf("Paths: %s\n", paths);
free(paths); // this causes a bus error
return 0;
}
如果我没有在最后调用free()
,它显示消息罚款和退出。如果我包含free()
调用,它会因总线错误而崩溃。在其他程序中,我还有其他呼叫free()
,也导致分段错误。
即使我自己为*paths
分配内存,free()
也会导致总线错误。试图释放内存导致崩溃有什么原因吗?
您需要张贴代码来说明您在上一段中提到的问题。 – 2010-04-18 15:17:36
你只能在使用malloc,calloc,realloc获得的内存上调用free。一些函数也会返回应该被释放的数据,比如strdup。但是getenv不会分配任何数据以供调用者使用。 http://www.manpagez.com/man/3/getenv/ – Ernelli 2010-04-18 15:19:12