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;
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:
#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()).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With