我有一个向字符串添加字符的函数:
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谢谢。
发布于 2010-12-29 02:34:38
调用realloc本身不会泄漏内存。你应该确保重新分配的字符串的内存在不再需要时释放。
发布于 2010-12-29 02:32:09
您的工具是否表明存在实际泄漏或潜在泄漏?
如果realloc()失败,像你这样使用realloc()会泄漏内存。在这种情况下,它将返回NULL,但不会释放原始块。因此,您将丢失指向该块的指针,并且无法释放它(除非该指针存储在其他地方)。
但这应该是很少见的(例如,当你耗尽内存时)。
如果这就是你的工具所抱怨的,你应该能够用下面这样的东西来修复泄漏警告:
void AddChToString(char **str,char ch){
int len=(*str)?strlen(*str):0;
char* tmp = realloc(*str, len+2);
if (!tmp) {
// whatever error handling is appropriate
}
(*str)=tmp;
(*str)[len]=ch;
(*str)[len+1]='\0';
}发布于 2010-12-29 02:35:25
我不知道关于realloc的实现问题,但这段代码中肯定存在内存泄漏的机会:来自realloc手册页:
如果
realloc()失败,原始块保持不变;它不会被释放或移动。
而且,由于realloc在失败时返回NULL,因此如果失败,您将丢失指向已经分配的内存块的唯一指针,因此存在内存泄漏。
要避免该问题,您应该执行以下操作:
char * temp=realloc(*str, len+2);
if(temp==NULL)
{
/* handle the error in some way */
}
else
*str=temp;https://stackoverflow.com/questions/4548385
复制相似问题