dynamic memory allocation!!! problem

Hello ,

As I am using pointers member variables in my code , I had to create a dynamic memory allocation . But when i tried to delete the allocated memory space I, the compiler crashes and I have no idea ..why??

my code :

Class A{
private:
int max_abc;
B* p_xyz; //B is some other class type
C ** p_abc; //C is some other class type
public:
A(int max_xyz =2, int max_abc =2);
A(const A & Copy); //copy constructor
~A();
}

//and my constructor is as below

A::A (int max_abc )
{
p_abc= new C*[max_abc];

p_xyz= new B;
}

//copy constructor - I had to do deep copy
A:: A(const A & copy)
{
max_abc = copy.max_abc;

p_xyz= new B;
p_xyz= copy.p_xyz;

m_abc = new C*[max_abc];
for(int j=0;j<max_abc;j++)
{
m_abc [j] = new C;
m_abc [j] = copy.m_abc[j];
}
}

//destructor definition

~A()
{
delete [] p_xyz;
for(int j=0;j<max_abc;j++)
{
delete m_abc [j];
}
delete [] m_abc ;
}


I seriously dont understand , why my compiler is crashed . Could some one please let me know, if my above definitions are correct\or reason for compiler crash ?? Please help....Thanks in advance!
Last edited on
In your copy constructor this:
1
2
    p_xyz= new B;
    p_xyz= copy.p_xyz;


is wrong. Assuming an appropriate overload for operator= can be found or generated you probably meant something like this:

1
2
    p_xyz= new B;
    *p_xyz= *copy.p_xyz;


You have similar problems with m_abc's elements.

Also, you cannot use delete[] on p_xyz as you didn't use new[] to allocate it.
Last edited on
Hello Cire ,

Thanks alot for your reply . I have modified the code as you suggested and it worked :)

I have one more question. Could you please let me know , what is the idea behind the method declaration below?

Class XYZ ::: method_xyz( Class* p_abc = NULL)

why is pointer initialized in the argument?

Thanks in advance!
XYZ::method_xyz has a default argument for its only argument so that if it is called without an argument, it will be as if it was called with the default argument.
Topic archived. No new replies allowed.