realloc()泄漏内存

我有一个函数,它为字符串添加一个字符:

void AddChToString(char **str,char ch){ int len=(*str)?strlen(*str):0; (*str)=realloc(*str, len+2); (*str)[len]=ch; (*str)[len+1]='\0'; } 

仪器(在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()失败, 那么像你一样使用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'; } 

我不知道有关realloc实现问题,但是在这段代码中肯定存在内存泄漏的机会:来自realloc联机帮助页:

如果realloc()失败,则原始块保持不变; 它没有被释放或移动。

并且,由于realloc在失败时返回NULL ,如果失败,则会丢失指向已分配的内存块的唯一指针,因此存在内存泄漏。

为了避免这个问题,你应该这样做:

 char * temp=realloc(*str, len+2); if(temp==NULL) { /* handle the error in some way */ } else *str=temp; 

尝试使用单独的变量重新分配,然后调用strcpy将str变量放入该空间,如下所示:

 void AddChToString(char **str,char ch){ char *blah; int len=(*str)?strlen(*str):0; blah=realloc(NULL, len+2); strcpy(blah, str); (*str)[len]=ch; (*str)[len+1]='\0'; }