【发布时间】:2019-09-09 17:43:38
【问题描述】:
我正在尝试一个简单的函数来理解使用 C 和 Valgrind 的分配/释放工作流。 Valgrind 的报告对我来说没有意义。
- 一个函数创建一个结构并返回一个指向堆中结构的指针。
- 指针指向的结构体填充在 main 中。
- 内容已打印出来。
- 调用释放结构。
- 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 不会报告内存泄漏。然而,这份报告让我感到惊讶。任何帮助表示赞赏!
【问题讨论】:
标签: c memory-leaks valgrind