I am trying to figure out if I'm having an idiot moment or if there really is a memory leak in libpcap. I'm running Ubuntu 17.10 and libpcap 1.8.1-5ubuntu1. It seems unlikely that such a mature library would have a leak.
I've cut out everything to make a MVCE, so as a consequence, this code doesn't really do much of anything except demonstrate the leak:
#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
int main(int argc, char **argv)
{
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t *fd = pcap_open_offline(argv[1], errbuf);
if (!fd) {
printf("error: %s\n", errbuf);
}
free(fd); fd = 0;
return 0;
}
The valgrind report (emphasis added):
==6871==
==6871== HEAP SUMMARY:
==6871== in use at exit: 262,696 bytes in 2 blocks
==6871== total heap usage: 4 allocs, 2 frees, 267,432 bytes allocated
==6871==
==6871== Searching for pointers to 2 not-freed blocks
==6871== Checked 73,072 bytes
==6871==
==6871== 262,144 bytes in 1 blocks are definitely lost in loss record 2 of 2
==6871==
==6871== LEAK SUMMARY:
==6871== definitely lost: 262,144 bytes in 1 blocks
==6871== indirectly lost: 0 bytes in 0 blocks
==6871== possibly lost: 0 bytes in 0 blocks
==6871== still reachable: 552 bytes in 1 blocks
==6871== suppressed: 0 bytes in 0 blocks
==6871== Reachable blocks (those to which a pointer was found) are not shown.
==6871== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==6871==
==6871== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
==6871== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
From the libpcap manpage , edited slightly:
pcap_fopen_offline()
return[s] a pointer to apcap_t
, which is the handle used for reading packets… To close a handle, usepcap_close()
.
free(fd)
just frees a single block of memory, since free()
knows nothing about the internals of a pcap_t
. In order to properly dispose of allocated resources, you need to use pcap_close(fd)
instead, as the documentation indicates.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.