我需要帮助,我只是学习C,不知道出了什么问题:
我在这里调用set_opts函数:
char * tmploc ;
tmploc=set_opts("windir","\\temp.rte");
printf(tmploc);
Run Code Online (Sandbox Code Playgroud)
(我知道,printf没有格式化,只是用于测试目的)
功能看起来像这样:
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;
}
Run Code Online (Sandbox Code Playgroud)
一切都很好,但是当我再试一次时:
char * tmploc2 ;
tmploc2=set_opts("windir","\\temp.rte");
printf(tmploc2);
Run Code Online (Sandbox Code Playgroud)
...程序刚刚终止
请告诉我我做错了什么
您使用分配字符串的长度env,但随后填充它getenv(env).如果getenv(env)比env那时长,你很有可能发生段错误.你的意思是用strlen(getenv(env))吗?
你真的应该为你的代码添加一些错误检查:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
654 次 |
| 最近记录: |