Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C程序malloc赋值返回NULL的可能原因?_C - Fatal编程技术网

C程序malloc赋值返回NULL的可能原因?

C程序malloc赋值返回NULL的可能原因?,c,C,我在64位Linux centos 5.7上使用gcc4.4.4和gdb,编译为ansi C。我不确定为什么我的代码在下面测试PDF==NULL时为true,并调用exit(2) 使用free-m,我在程序启动前观察: total used free shared buffers cached Mem: 2001 1955 46 0 71

我在64位Linux centos 5.7上使用gcc4.4.4和gdb,编译为ansi C。我不确定为什么我的代码在下面测试PDF==NULL时为true,并调用exit(2)

使用free-m,我在程序启动前观察:

             total       used       free     shared    buffers     cached
Mem:          2001       1955         46          0         71        975
-/+ buffers/cache:        907       1094
Swap:         4008        688       3319
以及当程序位于出口(2)上时;代码行,free-m表示:

             total       used       free     shared    buffers     cached
Mem:          2001       1970         31          0         72        976
-/+ buffers/cache:        921       1080
Swap:         4008        688       3319
在这两种情况下,缓存行、空闲列中都有大量可用内存(当然足够存储一个字节)

PDF变为空的其他可能原因是什么?什么样的编码错误会导致这种情况


如果有关系的话,我在上周一直在大量使用gdb,使用“q”然后“y”退出程序,而不是让它完成(计算所有malloc内存都会被终止的程序释放,因此不需要执行free()代码)。

如果您在某个地方写了超出缓冲区边界的内容,则可能损坏了堆,在这种情况下,所有的赌注都输掉了


我建议使用例如Valgrind来检查您是否没有这样做。

malloc
在调用进程无法分配更多内存时返回NULL,可能是因为系统调用失败,因为您达到了某些限制,如

即使某些内存可供其他进程使用,单个进程也可以达到其极限

您可以使用
strace
跟踪系统调用并找出哪个调用失败


并确保使用
gcc-Wall-g
(并使用调试器
gdb
)进行编译。

甚至不能分配一个字节(更新了上面的问题)。@ggkmath:没关系;如果堆被破坏,那么堆就被破坏了。事实上,更有理由相信堆被破坏了。在这之前,我对堆做了很多工作,所以这可能是原因。有没有什么好方法可以用gdb调试这个问题?@ggkmath:使用合适的内存调试器,比如Valgrind,会容易得多。它被设计来准确诊断这类问题。我们能看到重现该问题的示例(
main()
,includes和gcc标志)吗?
             total       used       free     shared    buffers     cached
Mem:          2001       1970         31          0         72        976
-/+ buffers/cache:        921       1080
Swap:         4008        688       3319