0

嗨,我有这个问题:

tmpy = (int**)realloc(os,y*sizeof(int*));
os = tmpy;
tmpy=NULL;
for(i=0;i<y;i++) {
    tmpx = (int*)realloc(os[i],x*sizeof(int)); 
    os[i] = tmpx;
    tmpx=NULL;
}

程序运行良好,但 valgrind 给出此错误:

==12513== Conditional jump or move depends on uninitialised value(s)
==12513==    at 0x402BF0D: realloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==12513==    by 0x8048760: main (main.c:55)
==12513==  Uninitialised value was created by a heap allocation
==12513==    at 0x402BF52: realloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==12513==    by 0x804871E: main (main.c:50)
==12513== 

怎么了?感谢您的帮助。

4

1 回答 1

2

假设dosrealloc()大小更大,那么int*有效添加的额外os将是未初始化的指针(由 访问os[i])。这些未初始化的指针最终被传递到循环realloc()内:for

tmpx = (int*)realloc(os[i],x*sizeof(int));

传递给的指针realloc()必须是NULL或 先前由malloc(),realloc()或返回的值calloc()。在进入循环之前将附加设置为int*。请注意,不需要对返回值进行强制转换。NULLforrealloc()

于 2012-12-02T22:29:01.223 回答