我目前正在尝试在C中实现setenv
函数,该函数设置环境变量的值,我担心由于strdup
而导致Valgrind标记的代码中的内存泄漏。我非常感谢您的见解,帮助我识别以下代码中的任何内存泄漏问题:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
extern char **environ;
int _setenv(const char *name, const char *value)
{
char **new_environ, *current_env, *env_name;
int count = 0, modified = 0, i = 0;
/* Count the number of environment strings */
while (environ[i])
{
count++;
i++;
}
/* Create a copy of the environment variable */
new_environ = malloc(sizeof(char *) * (count + 2));
if (!new_environ)
{
perror("Memory Allocation Error");
return (-1);
}
for (i = 0; i < count; i++)
{
current_env = strdup(environ[i]);
env_name = strtok(current_env, "=");
if (env_name != NULL && strcmp(env_name, name) == 0)
{
new_environ[count] = malloc(strlen(name) + strlen(value) + 2);
if (new_environ[count])
{
sprintf(new_environ[count], "%s=%s", name, value);
new_environ[count + 1] = NULL; /* Terminate the new array */
modified = 0;
free(current_env);
break;
}
}
else
{
new_environ[i] = current_env;
modified = 1;
free(current_env);
}
}
if (!modified)
{
new_environ[count] = malloc(strlen(name) + strlen(value) + 2);
if (new_environ[count])
{
sprintf(new_environ[count], "%s=%s", name, value);
new_environ[count + 1] = NULL; /* Terminate the new array */
}
}
else
{
new_environ[count] = NULL; /* Terminate the new array */
}
environ = new_environ;
return (0);
}
1条答案
按热度按时间yws3nbqq1#
更好的设计应该是:
我也不明白这一部分:
new_environ[i] = current_env
是一个 * 软拷贝 *,只将指针分配给指针数组。实际数据仍在原处。因此,如果你free(current_env)
,那么new_environ[i]
最终指向垃圾,因为你刚刚释放了它指向的数据。