C 中的内存泄漏是什么?

What are memory leaks in C?

我试着解决了exercise 16的额外学分。即使它编译正确,我也会出现内存泄漏。

现在我的想法是,如果根本不使用 malloc(),程序就不可能泄漏内存,但在这里确实如此,因为当我 运行 命令时:

valgrind --leak-check=full -v ./ex16-1

我得到了:

definitely lost: 21 bytes in 2 blocks

full output of valgrind is available on Pastebin

source code:

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

struct Person {
  char *name;
  int age;
  int height;
  int weight;
};

struct Person Person_create(char *name, int age, int height, int weight) {
  struct Person who;
  who.name = strdup(name);
  who.age = age;
  who.height = height;
  who.weight = weight;

  return who;
}

void Person_print(struct Person who) {
  printf("Name: %s\n", who.name);
  printf("\tAge: %d\n", who.age);
  printf("\tHeight: %d\n", who.height);
  printf("\tWeight: %d\n", who.weight);
}

int main(int argc, char const *argv[]) {
  struct Person joe = Person_create("Joe Alex", 32, 64, 140);
  struct Person frank = Person_create("Frank Blank", 20, 72, 180);

  Person_print(joe);
  Person_print(frank);
  return 0;
}

此程序显示出严重的内存泄漏。在许多系统上,它不会 运行 很远。

#include <memory.h>

int add (int a, int b)
{
      char *hog = malloc (1024 * 1024 * 1024 * 50);
      return a + b;
}
int main (void)
{
    int sum = add (add (6, 8), add (3, 7));
    return 0;
}

在您的程序中,它调用 strdup() 而调用 malloc。完成 strdup 的 return 值后,应该将其释放。

当你动态分配内存时,你有责任释放分配的内存,即将它还给OS,这样它可以在你失败时重新使用释放内存,结果发现内存足够,您的系统可能 运行 内存不足,导致所有 运行ning 程序失败,新程序将无法启动。

如果你不使用 malloc() 但你使用了一些库或标准库函数,那么泄漏就会发生,一种方法是

void function()
 {
    FILE *file;
    file = fopen("/some/path/file.txt", "r");
    /* check that file is valid and use it */
 }

上面的函数会泄漏内存,因为fopen()分配的一些资源没有释放,需要fclose(file)防止泄漏。

使用 valgrind 您可能会发现在代码中没有明显调用 malloc() 或任何相关函数的情况,但它会向您报告已分配内存并可能已释放内存。