I can't understand why there's a memory leak. Can someone please enlighten me ?

#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <math.h>
using namespace std;

class ChocBar{
	public:
		ChocBar(string name = "Barone",double price =1.20){
			name_ = name;
			price_ = price;			
		}
		
		string getName(){
			return name_;
		}
		
		double getPrice(){
			return price_;
		}
		
		void setName(string newName){
			name_ = newName;
		}
		
		void setPrice(double newPrice){
			price_ = newPrice;
		}
		
	private:	
		string name_;
		double price_;
};

class ChocStock{
	public:
		ChocStock(string a,double b,int c){	
			description_ = new ChocBar(a,b);		
			quantity_ = c;							 
		}
		
		~ChocStock()
		{
			delete description_;
		}
		
		ChocBar* getDes(){
			return description_;
		}	
		
	private:
		ChocBar *description_;
		int quantity_;
};

int main(){

	ChocStock a("Barone", 5.30, 10);
	ChocStock b = a;
	ChocStock c("Mars",3.25,20);
	c = a;               //this is causing the leak
	return 0;
}

here is part of the valgrind output

==27479== 29 (12 direct, 17 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==27479==    at 0x4023294: operator new(unsigned) (vg_replace_malloc.c:224)
==27479==    by 0x80488D5: main (QA3.C:40)
==27479== 
==27479== LEAK SUMMARY:
==27479==    definitely lost: 12 bytes in 1 blocks.
==27479==    indirectly lost: 17 bytes in 1 blocks.
==27479==      possibly lost: 0 bytes in 0 blocks.
==27479==    still reachable: 0 bytes in 0 blocks.
==27479==         suppressed: 0 bytes in 0 blocks.

Thanks!

Recommended Answers

All 3 Replies

put this inside your ChocStock class

ChocStock& operator=(const ChockStock& rhs){
 if(this!=&rhs){
  delete description;
  description_=new ChocBar(*rhs.description_);
  quantity_=rhs.quantity_;
 }
 return *this;
}

The reason you need to do this is because the shallow copy constructor simply copies the location of the description pointer in a to c, without deleting c's description. That's why you have a memory leak.

And, as an aside, you could update your use of the following libraries:
#include <stdlib.h>
#include <math.h>

should be
#include <cstdlib>
#include <cmath>

And as a rule if your class defines any of these 3 then you probably need all the 3.
1> destructor
2> copy ctor
3> assignment operator

so you can define a copy ctor as well for your class.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.