Malloc memory assigned pointer living on a static variable is auto freed or its really a leak?

83 Views Asked by At

Consider this case:

Using macos leaks -atExit -- have this code:

#include <stdlib.h>
int main(void)
{
    char *leak = malloc(100);
    return (0);
}

that is naturally a leak...which "leaks -atExit" is reporing correctly. then consider this:

#include <stdlib.h>
int main(void)
{
    static char *test = NULL;

    char *leak = malloc(100);
    test = leak;
    return (0);
}

now "leaks -atExit" is reporting no leaks. So what is going on?

are static pointers being auto free()'d at the end? regardless of being on the heap? or... this is really a leak, so its just "leaks tool" cant detect?

Would be cool to actually know whats happening...Thanks!

I cannot access, due to system limitations (old catalina system) to -fsanitize=leaks, nor valgrind, so i cannot test it outside leaks.

1

There are 1 best solutions below

2
DipStax On

Yes, your memory is lost when exiting.

Explanation:

When you create your static pointer, it will only allocat 32 or 64 bits (depend on your OS) to store the adress where it's pointing to.

So, when you are assigning the memory allocated on the heap to the static pointer, it will be like storing an int that represent the memory address of the first byte allocated.

When your programme exit, it will only "free" the memory address stored, and not what it's targeting.