繁体   English   中英

什么是 C 中的内存泄漏?

[英]What are memory leaks in C?

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

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

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

我有:

definitely lost: 21 bytes in 2 blocks
  • 即使我不分配任何内存(鉴于我的源没有任何问题),是否可能存在泄漏?
  • 另外,如果可能的话,我该如何释放那块内存? 记忆指向哪里?

valgrind完整输出可在 Pastebin 上获得

源代码

#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 的返回值后,它应该被释放。

当您动态分配内存时,您有责任释放分配的内存,即将其返回给操作系统,以便可以重用,如果您未能释放内存并且事实证明它有足够的内存,您的系统可能会耗尽内存,导致所有正在运行的程序失败,新程序将无法启动。

如果您不使用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()或任何相关函数的情况,但它会向您报告已分配的内存和可能已释放的内存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM