Reputation: 1
I need help, I'm just learning C, have no idea what is wrong:
Here I call set_opts
function :
char * tmploc ;
tmploc=set_opts("windir","\\temp.rte");
printf(tmploc);
( I know , that printf is not formated, just used it for testing purposes)
function looks like this :
char * set_opts(char * env,char * path){
char * opt;
opt=malloc(strlen(env)+strlen(path)+1);
strcpy(opt,getenv(env));
strcat(opt,path);
return opt;
}
Everything is ok, but when I try to call it again :
char * tmploc2 ;
tmploc2=set_opts("windir","\\temp.rte");
printf(tmploc2);
...program just terminates
Please tell me what I'm doing wrong
Upvotes: 0
Views: 823
Reputation: 49373
Be careful what you are doing with getenv()
, because:
The getenv() function returns a pointer to the value in the environment, or NULL if there is no match.
So if you pass a name that does not correspond to an existing environment variable then you get NULL returned and that is going to kill your strcpy(opt,getenv(env));
I recomend:
malloc()
returns and make sure that it is non-null.getenv()
returns and make sure that it is non-null.-Wall
.Upvotes: 4
Reputation: 23015
Are you sure: getenv(env) will fit into "opt" ? I don't think so. And if it doesn't fit, then the strcpy could kill your program.
A correction: char * set_opts(char * env,char * path){ char * opt; char * value = getenv(env); opt=malloc(strlen(value)+strlen(path)+1); strcpy(opt,value); strcat(opt,path); return opt; }
This way, you're sure you have enough space.
Upvotes: 0
Reputation: 612884
You allocate the length of the string using env
, but then populate it with getenv(env)
. If getenv(env)
is longer than env
then you have a good chance of a segfault. Did you mean to use strlen(getenv(env))
?
You really ought to add some error checking to your code:
char *set_opts(char *env, char *path)
{
char *opt;
char *value;
value = getenv(env);
if (value == NULL)
... handle error
opt = malloc(strlen(value)+strlen(path)+1);
if (opt == NULL)
... handle error
strcpy(opt,value);
strcat(opt,path);
return opt;
}
Upvotes: 6
Reputation: 72639
One possible reason: malloc returns NULL
and you never check for it. Same for getenv().
And it must be
malloc(strlen(getenv(env))+strlen(path)+1);
If the actual contents of getenv("windir") is longer than 6 characters, you write past the malloced buffer, which invokes undefined behavior.
Upvotes: 0
Reputation: 681
Try getting rid of getenv(env)
. Just put strcpy(opt,env);
. getenv()
is probably returning NULL
.
Upvotes: 0