gpt4 book ai didi

c - Valgrind 报告在函数中分配并在 main 中释放的结构泄漏

转载 作者:太空宇宙 更新时间:2023-11-04 05:32:21 24 4
gpt4 key购买 nike

我正在尝试一个简单的函数来理解使用 C 和 Valgrind 的分配/释放工作流程。 Valgrind 报告对我来说没有意义。

  1. 函数创建一个结构并返回指向堆中结构的指针。
  2. 指针指向的结构被填充到 main 中。
  3. 内容打印出来。
  4. 调用以释放结构。
  5. valgrind 在可执行文件上运行。

这是我的代码:

#include <string.h>

/* linked list abstraction */
struct ll {
void *data;
struct ll *prev;
struct ll *next;
};

/* struct to hold the data */
struct device {
char *name;
unsigned int major;
unsigned int minor;
struct ll sm; /* struct on stack */
};

/* error checked malloc */
static void *
ec_malloc(size_t size)
{
void *ptr = malloc(size);
if (unlikely(ptr == NULL)) {
perror("Error: ");
exit(-1);
} else {
return ptr;
}
}

struct device *
create_dev(char *, unsigned int, unsigned int);

int
main(int argc, char **argv)
{
struct device *dev = create_dev("Dev01", 1, 2);
printf("device: %s:%u:%u\n", dev->name, dev->major, dev->minor);
free(dev);
return 0;
}

struct device *
create_dev(char *name, unsigned int major, unsigned int minor)
{
struct device *dev = (struct device *)ec_malloc(sizeof(*dev));
dev->name = (char *)ec_malloc(BUFSIZE);
strcpy(dev->name, name);
dev->major = major;
dev->minor = minor;
return dev;
}

Valgrind 报告:


$ valgrind --leak-check=full ./devices
==1100== Memcheck, a memory error detector
==1100== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==1100== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==1100== Command: ./devices
==1100==
device: Dev01:1:2
==1100==
==1100== HEAP SUMMARY:
==1100== in use at exit: 15 bytes in 1 blocks
==1100== total heap usage: 3 allocs, 2 frees, 1,079 bytes allocated
==1100==
==1100== 15 bytes in 1 blocks are definitely lost in loss record 1 of 1
==1100== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==1100== by 0x108B7E: ec_malloc (devices.h:37)
==1100== by 0x108C3D: create_dev (main.c:84)
==1100== by 0x108BD3: main (main.c:35)
==1100==
==1100== LEAK SUMMARY:
==1100== definitely lost: 15 bytes in 1 blocks
==1100== indirectly lost: 0 bytes in 0 blocks
==1100== possibly lost: 0 bytes in 0 blocks
==1100== still reachable: 0 bytes in 0 blocks
==1100== suppressed: 0 bytes in 0 blocks
==1100==
==1100== For counts of detected and suppressed errors, rerun with: -v
==1100== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

我期待 Valgrind 报告没有内存泄漏。然而,这份报告让我感到惊讶。感谢您的帮助!

最佳答案

在释放 dev 之前,你需要先释放 dev->name

free() deallocates the memory previously allocated by a call to calloc, malloc, or realloc.

因此,一旦指针不再使用,请确保在上述函数分配的每个指针上调用 free()

关于c - Valgrind 报告在函数中分配并在 main 中释放的结构泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57858840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com