Reputation: 5144
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!
Upvotes: 3
Views: 227
Reputation: 1435
when you allocate some block of memory in C you should be responsible to free it using
free()
function.
if you want to make sure that your program won't crash due to some memory leaks.
you can use assert()
function when asking for more memory or using the allocated memory.
and you should check on the returned pointer returned from malloc , if it's NULL so the allocation failed. >> Be careful in linux kernels malloc()
won't return NULL ever,due to "memory overcommit"
Upvotes: 0
Reputation: 753525
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()
).
Upvotes: 4