如何通过putenv系统调用来维护内存?

Bil*_*eal 9 c++ unix system-calls

POSIX系统调用putenv表明调用后调用者无法释放分配的内存字符串putenv.因此,您无法putenv使用自动变量调用.

例:

#include <cstdlib>
#include <cstring>
#include <unistd.h>

int main()
{
    char envVar[] = "MYVAR=Value";
    // putenv(envVar); //ERROR!
    char *memory = static_cast<char*>(std::malloc(sizeof(envVar)));
    std::strcpy(memory, envVar);
    putenv(memory); //OK!
}
Run Code Online (Sandbox Code Playgroud)

我现在的问题是......环境变量记忆是怎样的free?是否需要将它们保持在单独的存储上并不断地从环境中移除东西?即

#include <cstdlib>
#include <cstring>
#include <string>
#include <map>

static std::map<std::string, char*> environmentBlock;

static struct EnvironmentBlockFreer
{
    ~EnvironmentBlockFreer()
    {
        for(std::map<std::string, char*>::iterator it = environmentBlock.begin()
            it != environmentBlock.end(); ++it)
        {
            putenv(it->first.c_str()); //Remove entry from the environment
            std::free(static_cast<void *>(it->second)); //Nuke the memory
        }
    }
} EnvironmentBlockFreer_ENTRY;

int main()
{
    char envVar[] = "MYVAR=Value";
    char *memory = static_cast<char*>(std::malloc(sizeof(envVar)));
    std::strcpy(memory, envVar);
    putenv(memory); //OK!
    environmentBlock.insert(std::pair<std::string, char*>(
        "MYVAR", memory)); //Remember the values for later!
}
Run Code Online (Sandbox Code Playgroud)

编辑:看起来我需要自己跟踪,至少根据Valgrind的说法:

/* This program: */

#include <stdlib.h>
#include <string.h>

int main()
{
        char str[] = "MYVAR=Example";
        char *mem = malloc(sizeof(str));
        strcpy(mem, str);
        putenv(mem);
}

/* Produced output:

==4219== Memcheck, a memory error detector
==4219== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==4219== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==4219== Command: ./a.out
==4219== 
==4219== 
==4219== HEAP SUMMARY:
==4219==     in use at exit: 14 bytes in 1 blocks
==4219==   total heap usage: 2 allocs, 1 frees, 194 bytes allocated
==4219== 
==4219== LEAK SUMMARY:
==4219==    definitely lost: 14 bytes in 1 blocks
==4219==    indirectly lost: 0 bytes in 0 blocks
==4219==      possibly lost: 0 bytes in 0 blocks
==4219==    still reachable: 0 bytes in 0 blocks
==4219==         suppressed: 0 bytes in 0 blocks
==4219== Rerun with --leak-check=full to see details of leaked memory
==4219== 
==4219== For counts of detected and suppressed errors, rerun with: -v
==4219== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 13 from 8)
*/
Run Code Online (Sandbox Code Playgroud)

Jon*_*ler 15

putenv()如果您担心内存泄漏,请不要使用.

这就是为什么POSIX提供了setenv()unsetenv(),以及-那些占用内存的控制和管理.


引用putenv()手册页(上面的URL):

putenv()函数应使用字符串参数来设置环境变量值.该字符串参数应指向表"的字符串name= value".该putenv()函数应通过更改现有变量或创建新变量,使环境变量名称的等于value.在任何一种情况下,字符串指向的字符串都应成为环境的一部分,因此更改字符串将改变环境.所使用的空间不再被使用一次,它定义了一个新的字符串名称传递给putenv().