Forum: PC-Programmierung Stringübergabe an putenv


von Klaus (Gast)


Lesenswert?

Moin!

Ich hab da mal ne Frage zu putenv.

Kann ich das innerhalb einer Funktion so aufrufen?
1
void init()
2
{
3
  string blafalse = "Variable=Wert";
4
  putenv(blafasel);
5
}

In dem Beispiel wird der String ja nach Ende der Funktion gelöscht. Mir 
hat nun jemand (der eigentlich wirlich Ahnung von C++ hat) erzählt, dass 
der übergebene String erhalten bleiben muss. Davon hab ich allerdings 
noch nie was gehört, und auch beim googlen keinen Hinweis darauf 
gefunden, dass das so sein müsste.

von Klaus (Gast)


Lesenswert?

sorry, sollte natürlich
1
putenv(blafasel.c_str());
heißen.

von Klaus W. (mfgkw)


Lesenswert?

Meine man-page sagt dazu:
1
NOTES
2
       The putenv() function is not required to be reentrant, and  the  one  in  libc4,
3
       libc5 and glibc 2.0 is not, but the glibc 2.1 version is.
4
5
       Description for libc4, libc5, glibc: If the argument string is of the form name,
6
       and does not contain an '=' character, then the variable name  is  removed  from
7
       the  environment.  If putenv() has to allocate a new array environ, and the pre‐
8
       vious array was also allocated by putenv(), then it will be freed.  In  no  case
9
       will the old storage associated to the environment variable itself be freed.
10
11
       The  libc4  and  libc5  and  glibc  2.1.2 versions conform to SUSv2: the pointer
12
       string given to putenv() is used.  In particular, this string  becomes  part  of
13
       the environment; changing it later will change the environment.  (Thus, it is an
14
       error is to call putenv() with an  automatic  variable  as  the  argument,  then
15
       return from the calling function while string is still part of the environment.)
16
       However, glibc 2.0-2.1.1 differs: a copy of the string is used.  On the one hand
17
       this  causes  a  memory leak, and on the other hand it violates SUSv2.  This has
18
       been fixed in glibc 2.1.2.
19
20
       The 4.4BSD version, like glibc 2.0, uses a copy.
21
22
       SUSv2 removes the const from the prototype, and so does glibc 2.1.3.

Insofern würde ich mich da auf nichts verlassen und keine
temporären bzw. automatischen Variablen dafür nehmen,
sondern entweder globale Variablen, statische Variablen oder
Konstanten.

Nachtrag: ... oder Speicher allokieren und allokiert lassen.

Bitte melde dich an um einen Beitrag zu schreiben. Anmeldung ist kostenlos und dauert nur eine Minute.
Bestehender Account
Schon ein Account bei Google/GoogleMail? Keine Anmeldung erforderlich!
Mit Google-Account einloggen
Noch kein Account? Hier anmelden.