【发布时间】:2011-05-31 16:59:31
【问题描述】:
我有一个向字符串添加字符的函数:
void AddChToString(char **str,char ch){
int len=(*str)?strlen(*str):0;
(*str)=realloc(*str, len+2);
(*str)[len]=ch;
(*str)[len+1]='\0';
}
Instruments(在 Mac 上)和 Valgrind 指示以下行: (*str)=realloc(*str, len+2) 正在泄漏内存。这是 realloc 的实现问题吗?还是我使用不当?
这是 Valgrind 的输出:
==39230== 6 bytes in 1 blocks are definitely lost in loss record 1 of 7
==39230== at 0x100018B2D: realloc (vg_replace_malloc.c:525)
==39230== by 0x100002259: AddChToString (in ./OpenOtter)
==39230== by 0x10000477B: QueryMapFromString (in ./OpenOtter)
==39230== by 0x100684CD2: ???
==39230== by 0x100001FB0: RequestHandler (in ./OpenOtter)
==39230== by 0x100065535: _pthread_start (in /usr/lib/libSystem.B.dylib)
==39230== by 0x1000653E8: thread_start (in /usr/lib/libSystem.B.dylib)
==39230==
==39230== 9 bytes in 1 blocks are definitely lost in loss record 2 of 7
==39230== at 0x100018B2D: realloc (vg_replace_malloc.c:525)
==39230== by 0x100002259: AddChToString (in ./OpenOtter)
==39230== by 0x10000298E: ParseHTTPRequest (in ./OpenOtter)
==39230== by 0x100004151: OpenRoutesFile (in ./OpenOtter)
==39230== by 0x10000142B: main (in ./OpenOtter)
==39230==
==39230== 45 bytes in 5 blocks are definitely lost in loss record 3 of 7
==39230== at 0x100018B2D: realloc (vg_replace_malloc.c:525)
==39230== by 0x100002259: AddChToString (in ./OpenOtter)
==39230== by 0x10000298E: ParseHTTPRequest (in ./OpenOtter)
==39230== by 0x100001EB4: RequestHandler (in ./OpenOtter)
==39230== by 0x100065535: _pthread_start (in /usr/lib/libSystem.B.dylib)
==39230== by 0x1000653E8: thread_start (in /usr/lib/libSystem.B.dylib)
==39230==
==39230== LEAK SUMMARY:
==39230== definitely lost: 60 bytes in 7 blocks
==39230== indirectly lost: 0 bytes in 0 blocks
==39230== possibly lost: 0 bytes in 0 blocks
==39230== still reachable: 1,440 bytes in 4 blocks
==39230== suppressed: 0 bytes in 0 blocks
谢谢。
【问题讨论】:
-
如果您不使用第一个间接寻址,为什么还要使用指向指针的指针?
-
您使用的是什么仪器?如果您使用的只是显示虚拟内存大小的东西,那么它不是问题(好吧,至少不是
realloc()的问题...另一方面,该代码) -
如果 realloc() 返回 NULL,你会丢失指向内存的指针。
-
@delnan:
realloc可能会返回与您传递给它的地址不同的地址。如果不使用双重间接,函数调用者将无法获得新地址。 -
"这是 realloc 的实现问题吗?" 否 “我是否使用不当?” 是的
标签: c string memory-leaks