Link to home
Start Free TrialLog in
Avatar of spiffles
spiffles

asked on

Dynamically Allocated Static Variable

if i have a function with a static local variable, that's dynamically allocated once:
int funct(void)
{
     static char* buffer = NULL;

     if (!buffer)
          buffer = malloc(SIZESLOW);
}

If there's no explicit free call, and if the process is killed; does this constitute as a leak? When the process is killed, is the heap essentially freed? I guess I'm after an in depth explanation on what happens on a windows platform (i imagine unix would be in the same boat)
Avatar of ozo
ozo
Flag of United States of America image

When the process is killed, memory is freed
Avatar of spiffles
spiffles

ASKER

And from an efficiency and/or design perspective would you use this kind of allocation?
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
> not guaranteed by the language
This is true.  The language specs say nothing about what happens after the program exits.
Yeah I'm doing some code reviews and was worried about a potential leak since there's no explicit free call. By the sounds of it, it's probably safe for the platform it's deployed on.

Closer inspection reveals SIZESLOW has elements which could be updated after a product restart. There's also a comment about dynamic allocation being used to avoid stack overflow. Anyways thanks ozo, efn for the feedback.

This is not specified by the language.  However, I have never heard of any compiler that does not release the memory when the program terminates.

Note that the behaviour is implementation specific but depends on the compiler run-time routines (in cooperation with the operating system in some implementations).

However, one important thing to note is that some run-time libraries may report this as a problem.  For example, Microsoft compilers have for some time been reporting this sort of allocation as a "memory leak" in debug builds, although a one-off allocation is not a "leak" more a "splash".  But if you rely on this reporting to find real memory leaks you may want to free the memory when the program terminates.  In C you can do this by registering a function pointer with atexit().
Yes atexit would be a good alternative, but since there's no precedence in the existing code based, I probably won't use it.