⇐ MY QUORA-INDEX QUORA - my answered Questions

QUORA - my answered Questions

Q025: How bad is using malloc and free in C? For example, is it recommended to use malloc and free 300,000 times in an application if I am allocating and freeing approximately 30 bytes? How is this dangerous?

allocate and free 30,000,000 30 bytes initialized objects in 144ms.

calloc() will use 4993ms (34 times slower).

This only works if you have a process which will build the data structures and after finish of that process you free all memory at once. I.e. not freeing single objects, which I would recommend generally because it frees you from manually doing memory management.

We only have allot(int size) and block_free_all(), allot can?t allocate objects larger than 1M in this example.

?How is this dangerous? why should this dangerous ? It?s probably as dangerous as drinking hot coffee, watch out what you are doing and you are fine.

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

typedef struct block_t {
	struct block_t *next;
	char memory[1024*1024];
} block_t;
block_t *blocks;
static void *block_current=0, *block_end=0;

static void block_add(void) {
	block_t *b=calloc(1, sizeof(block_t));
	b->next=blocks;
	blocks=b;
	block_current=b->memory;
	block_end=b->memory+sizeof(b->memory);
}

void *allot(int size) {
	if(block_current+size>=block_end) block_add();

	void *mem=block_current;
	block_current+=size;
	return mem;
}

void block_free_all(void) {
   block_t *b=blocks;
   while(b) {
      block_t *nb=b->next;
      free(b);
      b=nb;
   }
}

int main() {
   int i;
   for(i=0;i<30000000;i++) allot(30);
   block_free_all();

   return 0;
}


$ time ./x

real	0m0.144s
user	0m0.128s
sys	    0m0.011s