Deleting char array returned by getenv()
Asked Answered
U

2

5

Should I free the memory allocated for the char array, pointer to which is returned by the char * getenv( char * ) function? And which way - C free() or C+ delete []? If no - why?

I mean:

char * ptr = getenv( "LS_COLORS" );
cout << ptr << endl;
delete [] ptr; //Is this or free() call needed?

Thank you.

Urata answered 14/8, 2010 at 12:44 Comment(0)
C
5

The original data is stored in the environ variable (which is an array of char* and contains all environment variables with their values), getenv() only search for the corresponding variable name and returns the position of its value from the environ variable, so you don't have to free it, otherwise undefined behavior may be occurred.

Constrain answered 14/8, 2010 at 14:52 Comment(0)
D
4

Getenv returns a pointer to your processes environment. It does not need to be deallocated, and it is probably a good idea not to. (delete and free are probably smart enough to do nothing, but corrupting your environment is not a good idea.)

Dostie answered 14/8, 2010 at 12:52 Comment(1)
I wouldn't put any faith in delete or free being "smart enough to do nothing".Horn

© 2022 - 2024 — McMap. All rights reserved.