In my beginning programs in C, I noticed I call free a lot, so I thought of making a call-once function that frees up everything. Is this code a valid way of doing it, or are there any other suggestions to improve it?
#include <stdio.h>
#include <stdlib.h>
void *items_to_free[1024];
int intItemsToFree = 0;
void mm_init(void)
{
int i;
for (i = 0; i < 1024; i++)
{
items_to_free[i] = NULL;
}
}
void mm_release(void)
{
int i;
for (i = 0; i < 1024; i++)
{
if (items_to_free[i])
{
printf("Freeing %p\n", items_to_free[i]);
free(items_to_free[i]);
items_to_free[i] = NULL;
}
}
}
void mm_add(void *p)
{
items_to_free[intItemsToFree++] = p;
}
int main(void)
{
int *i = NULL;
/* initialize memory management */
mm_init();
/* allocate something */
i = (int *) malloc(sizeof(int) * 10);
/* add it to the memory collection */
mm_add(i);
/* run program as usual */
printf("App doing something...");
/* at the end, free all memory */
mm_release();
return 0;
}
Output:
App doing something...Freeing 0x100103b30