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);
}
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
char *path;
path = getenv("PATH");
printf("Current path = ", path);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
No that's not right.
getenv() returns a different address fro each different environment variable.
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
Regards
Friedrich
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?
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
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
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