【发布时间】:2011-04-10 02:24:22
【问题描述】:
我试图通过在此之前连接 str1 和 str2 在 UNIX 上使用 putenv()。 我想在环境中添加一个变量,或者修改一个变量,所以我正在调用 putenv()(或者我可以同样调用 setenv())。
基本上,我接收str1和str2,我创建str1=str2并将它作为参数传递给putenv()。
我展示的代码有效,但是当我取消注释 free() 调用时,它不会:不会为环境添加/修改变量。
size_t size = strlen(str1) + strlen(str2) + 2; // 2 is for the '\0' and the '='
char *tmp = (char *) malloc(sizeof(char) * size);
char *p;
int pos = 0;
// Copy first word
p = str1;
while (*p != NULL) {
tmp[pos++] = *p++;
}
// Add the '='
tmp[pos++] = '=';
// Copy second word
p = str2;
while (*p != NULL) {
tmp[pos++] = *p++;
}
// Add null character
tmp[pos] = '\0';
int ret = putenv(tmp);
if (ret != 0) {
perror("putenv failed");
}
//free(tmp); // This line is the problem when not commented
我为代码冗余道歉,我知道这两个 while 循环是相同的。我遇到的问题是,如果我取消注释 free 语句,然后调用“env”来打印环境,putenv 将不会添加值。
我不知道为什么会这样。现在让它工作,我有一个我不喜欢的内存泄漏。当我使用数组而不是指针时,它会产生与取消注释免费相同的问题。
有什么想法吗?
【问题讨论】:
标签: c unix memory-management free