Karim Dhrif
Karim Dhrif

Reputation: 91

What happens when you allocate on the heap, memory that is referenced in a static variable?

For a project written in C where global variables are not authorized, I used a singleton that returns a structure. Then I allocated some memory on a pointer that belongs to my structure. I am wondering about a few things. How does the memory is layed out when this is done ? Is there a better way of doing this ? My singleton.

static t_struct *r(void)
{
 static t_struct s;
 return (&s);
}

I allocate some memory.

void memory_allocation(int x)
{
 r()->a_ptr_to_another_struct = malloc(sizeof(t_another_struct) * (x));
 ...
}

Also it gets a bit complicated as I am forking the process a number of times. Each forks exit(). Should I free the static in each of my fork even though I am exiting ? I am getting some problems for not freeing things when exiting, if anyone has a good book or documentation so I can hold my ground I would be very grateful. I know that the kernel will reclaim memory on exit, but valgrind is not of this opinion. Would love any recommendation to study this design pattern more carefully as well as potential dangers.

Upvotes: 3

Views: 97

Answers (1)

dbush
dbush

Reputation: 225807

If you want valgrind to run clean, you'll need to free the memory in each process.

You can use an atexit handler, which gets called after a call to exit, to free the memory.

void clean_r(void)
{
    free(r()->a_ptr_to_another_struct);
}

And set it up at the start of your program:

atexit(clean_r);

Upvotes: 1

Related Questions