Problem with putenv() in global constructor

Gregory Shpitalnik gregory@il.marvell.com
Mon Jan 13 05:17:00 GMT 2003


Hi !

I found some strange putenv() function behavior when it's used in a
global object (C++ code).
constructor. I work on SPARC/Solaris 8 with g++/gcc version 2.95.3
20010315 (release).
Below is the C++ program that sets new (not existed yet) environment
variable MYPATH
with the help of putenv() C-function in the global object constructor.
It turned out that:
1. This environment variable setting is invisible within the main()
function
2. Resetting of this environment variable in the main() function causes
"freeing of non heap memory - attempting to free memory on the stack"
problem
(this is the message from Rational purify tool) within putenv() function

and does not change the environment variable.
It seems that something goes wrong within the data structure
that holds environment variables.

I compiled the program with "g++ -Wall test.cpp -o test".
------------------------------------------
// test.cpp

#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>


static const char* env_var = "MYPATH";

class MyClass
{
public:
     MyClass()
     {
           cout << env_var << " = " << getenv(env_var) << endl;
           char* value = (char*) malloc(100);
           strcpy(value, "MYPATH=/tmp:/users/gregory");
           putenv(value);
           cout << env_var << " = " << getenv(env_var) << endl;
     }
};

MyClass a;

int main(int argc, char *argv[])
{
  cout << env_var << " = " << getenv(env_var) << endl;
  char* value = (char*) malloc(100);
  strcpy(value, "MYPATH=gregory");
  putenv(value);
  cout << env_var << " = " << getenv(env_var) << endl;

  return 0;
}
-------------------------------------------
The output of the program is:
-----------------------------
MYPATH = (null)
MYPATH = /tmp:/users/gregory
MYPATH = (null)
MYPATH = (null)
-----------------------------

Is it a known problem ? Is it a feature or a bug ?

Thanks,

Gregory Shpitalnik
gregory@il.marvell.com

-------------- next part --------------
A non-text attachment was scrubbed...
Name: gregory.vcf
Type: text/x-vcard
Size: 180 bytes
Desc: Card for Gregory Shpitalnik
URL: <http://gcc.gnu.org/pipermail/gcc-bugs/attachments/20030113/d78c75dd/attachment.vcf>


More information about the Gcc-bugs mailing list