c - VS2012 上 getenv/putenv 的内存损坏

标签 c environment-variables visual-studio-2012

尝试运行以下在 VS2012 中编译的代码时,我似乎遇到了内存损坏。

它在 VS2010 和以前的版本中工作正常:

char *var1 = getenv("var1");  // Value for var1 is correct here

char var2S[MAXSTRING];

sprintf(var2S, "VAR2=%s/a/%s/b", var1, getValue());  //Var2 looks correct

static const char *env_string = strdup(const_cast<char *>(var2S));

putenv((char *)env_string); // Value for var1 is corrupt after this call

最佳答案

getenv() 返回指向环境进程全局副本的指针。来自 MSDN:

getenv and _putenv use the copy of the environment pointed to by the global variable _environ to access the environment

所以 var1 指向那组数据。一旦您调用 putenv(),该全局数据就会被修改,并且 var1 指针指向更改的内存。您需要将 var1 指向的数据复制到您自己的缓冲区中以修改环境,或者再次调用 var1 = getenv("var1") 以“刷新”指针。

请注意,在 your answer 中您指出使用 getenv_s() 可以为您解决问题。这是因为 getenv_s() 将环境字符串复制到您提供的缓冲区中,而不是返回一个处于全局 _environ 状态的指针,该状态稍后可能会更改。

关于c - VS2012 上 getenv/putenv 的内存损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11301601/

相关文章:

c++ - 如何实现内存堆

c - 如何通过C编写的cgi-bin程序检索表单 "POST"数据

c++ - 将 std::chrono::system_clock::time_point::min() 转换为字符串时出现无效空指针错误

eclipse - 使用 &get_instance() 时如何获得 CI 的完整 Eclipse 代码?

c++ - 错误 C2248 : 'CvSVM::CvSVM' : cannot access private member declared in class 'CvSVM'

visual-studio-2012 - "Run as different user"Visual Studio,无法清除缓存的 TFS 凭据

c - 如何用kmalloc进行数据结构对齐?

c++ - 从进程加载的 DLL 调用另一个进程中的方法

c - 我的 strlen 代码出现段错误

docker - 在DockerFile中使用Dokku Environment变量