Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep track of how much memory is leaked?

I'm working on a homework assignment that requires me to write a program that leaks memory, keep track of how much memory it is leaking until it crashes.

My general thoughts for the program would be to continuously reassign a malloc pointer.

Here's my code so far:

char *oldMemory = malloc(125000); //1MB of memory.
char *newMemory = malloc(125000);
oldMemory = newMemory;
  • Is there are way to put this in a loop and repeatedly orphan a certain amount of memory until the program can no longer allocate any memory and crashes?
  • How can I keep track of how much memory was leaked before the program crashed?

Thanks for your time and expertise!

like image 322
Nathan Jones Avatar asked Jan 20 '26 11:01

Nathan Jones


1 Answers

  1. Yes.
  2. Count the size of the leaked allocations.

Don't forget to print the size leaked on each iteration - so you see the result even if the program crashes. The program should not crash if you test for failed allocations before accessing it.

Hence:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

enum { ALLOCSIZE = 125000 };

int main(void)
{
    long long size = 0;
    char *space = malloc(ALLOCSIZE);
    while (space != 0)
    {
        size += ALLOCSIZE;
        printf("OK %lld\n", size);
        memset(space, '\0', ALLOCSIZE);
    }
    return(0);
}

The Linux OOM might confuse things; it allows over-commitment of memory. You'd have to access the allocated memory before leaking it - hence the memset() (or you could use calloc() instead of malloc()).

like image 79
Jonathan Leffler Avatar answered Jan 23 '26 05:01

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!