Call munmap() in a timely manner after use to unmap the memory mapped via mmap(). Otherwise, the virtual address space cannot be reclaimed, causing memory leaks.
// rules.json
{
"rules": {
"cpp": {
"ResourceLeak": [
{
"ruleId": "MemoryMap API Not Paired",
"severity": "error",
"skip": false
}
]
}
}
} // Positive example
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
void MapMemoryWithUnmap()
{
int fd = open("/path/to/file", O_RDONLY);
if (fd == -1) return;
void *mapped = mmap(nullptr, 4096, PROT_READ, MAP_PRIVATE, fd, 0);
if (mapped == MAP_FAILED) {
close(fd);
return;
}
// Use the mapped memory.
// Properly unmap the memory.
munmap(mapped, 4096);
close(fd);
} // Negative example
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
void MapMemoryWithoutUnmap()
{
int fd = open("/path/to/file", O_RDONLY);
if (fd == -1) return;
// Map the memory.
void *mapped = mmap(nullptr, 4096, PROT_READ, MAP_PRIVATE, fd, 0);
if (mapped == MAP_FAILED) {
close(fd);
return;
}
// Use the mapped memory.
// Not unmapped - address space leak!
close(fd);
} For details about how to configure Code Scanner check rules, see Using codescanner.