此代码中的内存泄漏在哪里以及如何解决?

时间:2010-08-29 14:03:37

标签: c memory-leaks valgrind

在我的项目中,我有一个从整数创建字符串的方法(使用strcat)并将其写入文件。不幸的是它确实有内存泄漏。在跟踪泄漏时,我将代码简化为以下内容。我似乎无法找到甚至修复它。这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[] )
{
 char* output = "\0";
 int counter = 5;
  while(counter > 0)
  {
      char buffer[20];
      sprintf(buffer, "%u", counter);
      char* temp;
      temp = malloc((strlen(output) + strlen(buffer) + 1));
      strcpy(temp, buffer);
      strcat(temp, output);
      char* oldmemory = output;
      output = temp;
      free(oldmemory);
      counter--;
  }
printf("output: %s\n", output);
free(output);
return 0;
}

Valgrind 返回:

==7125== Memcheck, a memory error detector
==7125== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==7125== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==7125== Command: ./foo
==7125== Parent PID: 4455
==7125== 
==7125== Invalid free() / delete / delete[]
==7125==    at 0x4024B3A: free (vg_replace_malloc.c:366)
==7125==    by 0x8048662: main (foo.c:20)
==7125==  Address 0x8048780 is not stack'd, malloc'd or (recently) free'd
==7125== 
==7125== 
==7125== HEAP SUMMARY:
==7125==     in use at exit: 0 bytes in 0 blocks
==7125==   total heap usage: 5 allocs, 6 frees, 20 bytes allocated
==7125== 
==7125== All heap blocks were freed -- no leaks are possible
==7125== 
==7125== For counts of detected and suppressed errors, rerun with: -v
==7125== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 15 from 8)

内存泄漏在哪里?我该如何解决?

4 个答案:

答案 0 :(得分:9)

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[] )
{
 char* output = "\0";

字符串文字是'\ 0'自动终止,你不需要添加它。

 int counter = 5;
  while(counter > 0)
  {
      char buffer[20];
      sprintf(buffer, "%u", counter);
      char* temp;
      temp = malloc((strlen(output) + strlen(buffer) + 1));
      strcpy(temp, buffer);
      strcat(temp, output);
      char* oldmemory = output;
      output = temp;
      free(oldmemory);

第一次调用free()时,它释放输出的初始值,这是指向字符串文字"\0"的指针。对free()*alloc()返回的有效指针以外的任何内容调用NULL是未定义的行为。

      counter--;
  }
printf("output: %s\n", output);
free(output);
return 0;
}

valgrind报道:

==7125== Invalid free() / delete / delete[]
==7125==    at 0x4024B3A: free (vg_replace_malloc.c:366)
==7125==    by 0x8048662: main (foo.c:20)
==7125==  Address 0x8048780 is not stack'd, malloc'd or (recently) free'd

这不是内存泄漏;这是无效的free()

答案 1 :(得分:4)

您的代码已损坏。第一次通过,你将oldmemory设置为输出,其中输出指向未在堆上分配的内存。之后,您尝试释放此内存。这会生成关于释放未通过malloc分配的内存的valgrind错误。因此,您分配的原始内存永远不会被释放。

答案 2 :(得分:3)

你的应用程序崩溃试图释放(“\ 0”)。 (只需注意,如果你想要一个空字符串,“”就够了,“\ 0”实际上就是字符串\ 0 \ 0。

而不是使用malloc和strcpy,看看realloc,它会做你想要的一切但更好:)但你很可能想要构建你的字符串前进(counter = 0; counter&lt; 5; count ++)而不是去向后

答案 3 :(得分:1)

如果你想使用这个算法,应该用malloc分配输出点的初始空间,因此:

 char *output = malloc(1);
 if(!output) { /* handle error */ }
 output[0] = '\0';
 ... rest of code as is ...

字符串文字不会与malloc一起分配,因此不能free编辑,这是您问题的根源。