cmallocfree

Memory slice using malloc by slicing one big malloc'd memory


Consider an application that invokes malloc() and free() many times. The application allocates a total of say 1000 bytes in total.

I am trying to write a code where we reduce number of malloc / free calls by slicing one big malloc'd memory and then freeing it up:

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

struct A
{
    char *s;
    int data;
};

struct B
{
    float len;
    char net;
    int data[];
};

struct C
{
    float len;
    char net;
    int data[10];
    struct B *b;
}; 

int main() {
    int s =0;
    char *p = malloc(1000);
    char *mem = p;
    //Alocate for struct A from above pool
    struct A *a = (struct A *)p;
    p += sizeof(struct A);
    struct B *b = (struct B *)p ;
    p += sizeof(struct B) + sizeof(int) * 3; //data[0]..data[2]
    struct C *c = (struct C *)p;
    free(mem);
    return 0;
}

Is this a legitimate approach for my issue? Is there any flaw in my code or scenarios that I have missed and can cause problem?


Solution

  • It sounds like what you're looking for is an arena allocator, and it's a perfectly normal technique in some contexts.

    Once you've fixed the alignment issue, and organised your code as a deliberate and self-contained arena, you'll find

    Sometimes it makes sense not to worry about deallocation at all, until reset. That sidesteps the first two points, but whether it is acceptable depends entirely on your allocation patterns (and how much memory you can afford to waste).

    Knowing the name of the technique, it should be easy to find working examples.