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!
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:
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 usecalloc()instead ofmalloc()).