Bug 18515

Summary: Memory leak in putenv
Product: Base System Reporter: Abdul Khan <khana>
Component: binAssignee: freebsd-bugs (Nobody) <bugs>
Status: Closed FIXED    
Severity: Affects Only Me    
Priority: Normal    
Version: 1.0-RELEASE   
Hardware: Any   
OS: Any   

Description Abdul Khan 2000-05-12 17:50:01 UTC
 I think I may have come up with a work around:
 
 #include <iostream.h>
 #include <stdlib.h>
 
 extern char** environ;
 
 class Exception
 {
 	public:
 		virtual char* getErrorMessage() = 0;
 };
 
 class NullPointerException : public Exception
 {
 	public:
 		virtual char* getErrorMessage() 
 		{
 			return "Null Pointer Exception";
 		};	
 };
 
 class EnviornmentVariable 
 {
 	public:
 
 		EnvironmentVariable(char* variable_name) 
 		{ 
 			if (!variable_name) throw NullPointerException();
 			else name = strdup(variable_name); 
 		};
 
 		void setEnv(char* value)
 		{
 			int i = 0, j = 0;
 			while (environ[i])
 			{
 				while (name[j] && environ[i][j] &&
 							name[j] == environ[i][j]) j++;
 				if (environ[i][j] == '=' && !name[j]) 
 				{
 					environ[i] = (char*) realloc (environ[i],
 											strlen (value) + strlen (name) + 1 + 1);
 					sprintf(environ[i], "%s=%s", name, value);
 					break;
 				}
 				i++;
 			}
 		}
 
 		void setEnvWithLeak(char* value)
 		{
 			char* env = (char *) malloc (strlen (value) + strlen (name) + 1 + 1);
 			sprintf(env, "%s=%s", name, value);
 			putenv(env);
 		}
 
 		virtual ~EnvironmentVariable() { free(name);};
 	private:
 		char* name;
 	};
 
 
 int main(int argc, char** argv)
 {
 char * str = 0;
 try 
 {
 	if (argc < 4) 
 	{
 		cout << "Usage: env_mem_leak <environment variable name> ";
 		cout << "<iterations> <bifurcations>" << endl;
 		cout << "Where iterations is the number of times to set the variable ";
 		cout << "and bifrucations is the number of changes in the length of "; 
 		cout << "the string that is put into the environment variable" << endl;
 	}
 	
 	EnvironmentVariable myenv(argv[1]);
 	int iterations = atoi(argv[2]);
 	int bifurcations = atoi(argv[3]);
 	str = (char*) malloc(sizeof(char)*(bifurcations+1));
 
 	for (int i=0; i < iterations; i++)
 	{
 		memset(str, 'A', i % bifurcations);
 		str[(i % bifurcations) + 1]='\0';
 
 		myenv.setEnv(str);
 			////switch these to see the memory leak problem in purify!!!!!!!!!!
 		//myenv.setEnvWithLeak(str);
 
 	}
 
 } 
 catch(Exception& e) 
 {
 	cout << endl << e.getErrorMessage() << endl;
 };
 if (str) free(str);
 return 0;
 }
Comment 1 Jeroen Ruigrok van der Werven freebsd_committer freebsd_triage 2000-05-13 11:57:23 UTC
Responsible Changed
From-To: gnats-admin->freebsd-bugs

Misfiled/botched PR.  Severity and priority left at default value. 
Memory leaks are IMHO serious. 
Comment 2 Steve Price freebsd_committer freebsd_triage 2000-05-28 15:47:03 UTC
State Changed
From-To: open->closed

See also bin/18519.