Link to home
Start Free TrialLog in
Avatar of BackupName
BackupName

asked on

Do i have to allocate and free memory

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);
}
ASKER CERTIFIED SOLUTION
Avatar of zebada
zebada

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
Avatar of F. Dominicus
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
Avatar of zebada
zebada

No that's not right.
getenv() returns a different address fro each different environment variable.
You are right. It seems I have messed that up with some other function.

Regards
Friedrich
Avatar of BackupName

ASKER

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.
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?
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