views:

59

answers:

3

I have a very simple test program, running on Solaris 5.8:

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

int main(void)
{
    char *paths;
    paths = getenv("PATH");
    printf("Paths: %s\n", paths);

    free(paths); // this causes a bus error
    return 0;
}

If I don't call free() at the end, it displays the message fine and exits. If I include the free() call, it crashes with a bus error. I've had other calls to free(), in other programs, cause segmentation faults as well.

Even if I allocate the memory for *paths myself, free() will cause a bus error. Is there some reason trying to free up the memory is causing a crash?

+6  A: 

Because you're not supposed to free the value returned from getenv() (it's a static variable).

KennyTM
don't free it unless you know where it came from!
Tom Dignan
So even if I allocate the memory ahead of time, some functions just kind of override that and I shouldn't touch it?
chucknelson
@chuck: Like `char* paths = malloc(123); paths = getenv("PATH");`? The pointer to the malloc-ed memory will be overridden so it'll just be leaked.
KennyTM
Ah got it - I need to start paying closer attention to the documentation! Thanks all!
chucknelson
+1  A: 

The memory returned by getenv() is not allocated by malloc() and should therefore not be freed by free(). In general, none of the C standard library functions that are not part of the malloc() family should be freed using free(), or in fact freed at all.

anon
+1  A: 

The string pointed by the pointer returned by this function shall not be modified by the program.

It's not your memory to free.

FigBug