I wrote this little version of malloc (no free):
#include <cstdio>
#include <cstddef>
#include <unistd.h>
#define word_size sizeof(intptr_t)
#define align(n) ((n + word_size - 1) & ~(word_size - 1))
void* my_malloc(size_t size) {
void* p = sbrk(0);
printf("before allocation: %p\n", p);
if (sbrk(align(size)) == (void*) -1) {
// failed to allocate memory
return NULL;
}
printf("after allocation: %p\n", sbrk(0));
return p;
}
int main() {
int* foo = (int*) my_malloc(1);
*foo = 100;
printf("after allocation outside: %p\n", sbrk(0));
}
Here is the output of the code:
before allocation: 0x1796000
after allocation: 0x1796008
after allocation outside: 0x1796008
As you can see, the memory allocated by my_malloc has not been freed.
Yet when I run it through valgrind with this:
valgrind --leak-check=yes ./main
I get this:
==1592== Memcheck, a memory error detector
==1592== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==1592== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==1592== Command: ./main
==1592== HEAP SUMMARY:
==1592== in use at exit: 0 bytes in 0 blocks
==1592== total heap usage: 2 allocs, 2 frees, 73,728 bytes allocated
==1592==
==1592== All heap blocks were freed -- no leaks are possible
==1592==
==1592== For counts of detected and suppressed errors, rerun with: -v
==1592== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
As you can see, valgrind didn't find any memory leaks! Am I using valgrind incorrectly, or is this a bug?