How to free memory ?

This is a discussion on How to free memory ? within the C++ Programming forums, part of the General Programming Boards category; This is my code for operator overloading; where should i free memory in class with distructor ? if i do ...

  1. #1
    Registered User
    Join Date
    Mar 2007
    Location
    India
    Posts
    17

    How to free memory ?

    This is my code for operator overloading;
    where should i free memory in class with distructor ? if i do that i am getting exception.

    Code:
    --------------------------------
    in Test.h file
    ----------------------------------
    
    class demon
    {
    	
    	char* pName;
    	int nVal,nLen;
    	
    public:
    	demon operator= (const demon& d)
    	{
    		if(this != &d)
    		{
    			this->pName = new char(strlen(d.pName)+1);
    			strcpy(pName,d.pName);
    			this->nVal = d.nVal;
    		}
    		return *this;
    	}
    	void set(int x,char* pstring)
    	{
    		nVal = x;
    		pName = (char*)malloc(strlen(pstring)+1);
    		strcpy(pName ,pstring);
    		
    	}
    	void get()
    	{
    		cout<<nVal<<endl<<pName<<endl;
    	}
    	
    	demon operator + (const demon& d1)//,const demon d2);
    	{
    		
    		nLen =strlen(this->pName)+1;
    		nLen += strlen(d1.pName)+1;
    		
    		this->pName = (char*)realloc(this->pName,nLen);
    		strcat(this->pName, d1.pName);
    		
    		return *this;
    	}
    	
    };
    
    
    ------------------------------------
    in test.cpp fiel
    ---------------------------------------
    
    void main()
    {
    	
    	demon obj_demon, obj_demon2  ;
    	
    	obj_demon.set(25,"mySample");
    	obj_demon2.set(45,"Overload demo"); //   = obj_demon1 = obj_demon;
            obj_demon =  obj_demon + obj_demon2; 
    	
    	obj_demon.get();
    	obj_demon2.get();
    	return;
    }

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,592
    > where should i free memory in class with distructor ?
    Yes, you should free memory in the destructor.

    > if i do that i am getting exception.
    That's because your code is full of bugs.
    1. You don't have a proper constructor to begin with, which at least sets pName = NULL;
    2. Mixing new and malloc/realloc is a bad thing to do. Since this is C++, you should be using new for everything.

    > void main()
    See the FAQ - main returns int.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    You should really use std::string instead of char* in which case you wouldn't need practically any of this code.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  4. #4
    Registered User
    Join Date
    Mar 2007
    Location
    India
    Posts
    17
    thx salem,
    Did operator "new" resembles to "realloc" functionality ?
    say i initilization for pointer in constructor and free memory in destructor. still my code
    gives run time error at destructor.
    i have just switched from C to C++ programming.

    Code:
    ---------------
    test.h file
    ---------------------------
    class demon
    {
    	
    	char* pName;
    	int nVal,nLen;
    	
    public:
    	
    	demon():nVal(0),nLen(0)
    	{
    	pName = NULL;
    	}
    	
    	
    	demon operator= (const demon& d)
    	{
    		if(this != &d)
    		{
    			this->pName = new char(strlen(d.pName)+1);
    			memset(this->pName,0,strlen(d.pName)+1);
    			strcpy(pName,d.pName);
    			this->nVal = d.nVal;
    		}
    		return *this;
    	}
    	
    	
    	void set(int x,char* pstring)
    	{
    		nVal = x;
    		pName = (char*)malloc(strlen(pstring)+1);
    		memset(this->pName,0,strlen(pstring)+1);
    		strcpy(pName ,pstring);
    	}
    	
    	void get()
    	{
    		cout<<nVal<<endl<<pName<<endl;
    	}
    	
    	demon operator + (const demon& d1)//,const demon d2);
    	{
    		
    		nLen =strlen(this->pName)+1;
    		nLen += strlen(d1.pName)+1;
    		
    		this->pName = (char*)realloc(this->pName,nLen);
    
    		memset(this->pName,0,nLen);
    		strcat(this->pName, d1.pName);
    		return *this;
    	}
    
    	~demon()
    	{
    	delete(pName);
    	}
    	
    };
    
    -----------------------
    in test.cpp file
    ---------------------------
    main()
    {
    	
    	demon obj_demon, obj_demon1, obj_demon2  ;
    	
    	obj_demon.set(25,"mySample");
    	
    	obj_demon2.set(45,"Overload demo");
    	
        obj_demon =  obj_demon + obj_demon2; 
    	
    	
    	obj_demon.get();
    	obj_demon2.get();
    	
    	return 0;
    }
    Last edited by Brw_Abhi; 06-04-2007 at 06:11 AM.

  5. #5
    The larch
    Join Date
    May 2006
    Posts
    3,573
    To allocate a char array use square brackets:
    Code:
    pName = new char[how_many];
    ...
    delete [] pName;
    In addition you'll need a copy constructor. And the assignment operator leaks memory because you don't free the old memory before you request for new memory.

    You shouldn't be using realloc with a pointer that you obtained with new (in C++ you'd just free previous memory and allocate a larger new block).

    By the way, for a char* alloc, free and realloc would be fine if you want to stick with char arrays. If you want to write programs, though , and not just sweat over the low-level char array manipulation, strings are preferable.

    Here's what the same code would look like, using C++ string class.

    Code:
    #include <string>
    
    class demon
    {
    	
    	string Name;
    	int nVal;
    	
    public:
    	
    	demon():nVal(0) {}	
    			
    	void set(int x, string s)
    	{
    		nVal = x;
    		Name = s;
    	}
    	
    	void get()
    	{
    		cout<<nVal<<endl<<Name<<endl;
    	}
    	
    	demon operator + (const demon& d1)
    	{
    		
    		Name += d1.Name;
    		return *this;
    	}	
    };
    Note, that neither copy constructor, assignment operator nor destructor is needed, as the default ones that the compiler produces are good enough.
    Last edited by anon; 06-04-2007 at 07:09 AM.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,592
    > Did operator "new" resembles to "realloc" functionality ?
    There is no C++ operator which resembles realloc in C.
    You have to call new[ ] for some new memory, followed by a manual copy in your code (use a for loop), and a delete[ ] of the old memory.

    And you're still mixing new with malloc/realloc.

    > demon():nVal(0),nLen(0)
    Why not
    demon():nVal(0),nLen(0),pName(0)

    > main()
    It's better than void, but why not just be specific and say
    int main()
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  7. #7
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    > Did operator "new" resembles to "realloc" functionality ?
    If you use C++ vectors instead of dynamic arrays (generally a good idea), you can use what's known as the "swap trick" to do essentially what realloc() does with dynamic arrays. For example, see

    http://www.informit.com/guides/conte...eqNum=268&rl=1

  8. #8
    Registered User
    Join Date
    Mar 2007
    Location
    India
    Posts
    17
    Thanks to all for your valuable suggestions.
    I will try to skick more to c++ manual.

  9. #9
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,307
    operator + should not modify either of the operands. Declare the function as const and correct the behaviour, or better yet, use the two-parameter friend version with both parameters as const.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with shared memory shmdt() shmctl()
    By Jcarroll in forum C Programming
    Replies: 1
    Last Post: 03-17-2009, 10:48 PM
  2. Replies: 7
    Last Post: 02-06-2009, 11:27 AM
  3. How to Free All Memory ?
    By sergioms in forum C Programming
    Replies: 52
    Last Post: 01-15-2009, 04:02 PM
  4. Memory leak with detached pthreads - how to free?
    By rfk in forum Linux Programming
    Replies: 2
    Last Post: 08-17-2007, 06:50 AM
  5. free memory in structure
    By franziss in forum C++ Programming
    Replies: 22
    Last Post: 01-08-2007, 04:16 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21