Do i have to allocate and free memory

BackupName
BackupName used Ask the Experts™
on
Do i have to allocate and free memory for path in the following program, and why?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
  char *path;

  path = getenv("PATH");

  printf("Current path = ", path);
}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
No.

The getenv function returns a pointer to the string value of "PATH".
The pointer will point to a memory location in your program's environment.
The program's environment is allocated/deallocated by the operating system.

fridomCEO/Programmer

Commented:
Well you better make a copy of the returned string. If you do this

path = getenv("SOME_VAR");

some computation
and than

path1 = getenv("SOME_OTHER_VAR);

you will lost the content of path. So the "right" thing to do is makeing a copy of value returned by getenv.

Regards
Friedrich

Commented:
No that's not right.
getenv() returns a different address fro each different environment variable.
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

fridomCEO/Programmer

Commented:
You are right. It seems I have messed that up with some other function.

Regards
Friedrich

Author

Commented:
How do I recognize functions that return memory that is allocated/deallocated by the operating system.  Can you show me an example of other functions that work this way? And thanks.

Commented:
You ned to read the documentation to understand return values and how they may be used.

Off the top of my head I do not know of any other functions that work like getenv().

Anyone else know?
fridomCEO/Programmer

Commented:
Well the only thing that really helps is a up-to-date documentation. Anyway therea are some hints that memory allocation is around if there is a some sort of "free" function. Example is fopen and fclose, open and close
malloc and free ;-), regfree.

I do not know any Standard C function which do require an explicitly free after usage. You just have to be careful about extern libraries. Which anyway should state their requirements very clearly.

Regards
Friedrich

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial