I’m trying to use mallinfo2 to get a snapshot of how many bytes of memory are allocated at a particular time for testing purposes, however it’s not behaving as I would expect. My understanidng is that mallinfo2().uordblks should reflect the current amount of memory in-use by mallocs. When a chunk of memory is freed uordblks should decrease accordingly. However, this is not what I’m seeing at all.
I wrote this simple program, malltest.c:
#include <malloc.h>
int main(void) {
char *myptr;
printf("Value before malloc %zun", mallinfo2().uordblks);
myptr = malloc(sizeof(char));
printf("Value after malloc %zun", mallinfo2().uordblks);
free(myptr);
printf("Value after free %zun", mallinfo2().uordblks);
return 0;
}
Running it produces this output:
# gcc malltest.c
# ./a.out
Value before malloc 0
Value after malloc 1728
Value after free 1728
I was expecting uordblks to increase by the size of a memory chunk after the malloc, and then reduce back to 0 after the free. Clearly I am misunderstanding something here. Why does uordblks behave this way, and is there an alternative that accomplishes what I’m actually looking to do?
jasperd is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.