-3

I am using shallow copy to copy one object to another object and when main() goes out of scope destructors are called and error ": double free or corruption (fasttop):" is thrown which is perfectly fine as I am using shallow copy. Now when I am creating another object between the two copies, it doesn't throws any error, which is bugging me.

int main(int argc, char *argv[])
{   
    int n =5;

    vector vec(n);  
    vector vec1(vec);   
    cout<<vec<<endl;
    cout<<vec1<<endl;

    return 0;
}

which gives output Which is expected as I am using shallow copy Now when I am adding one more object in between, then no error is thrown

int main(int argc, char *argv[])
{   
    int n =5;

    vector vec(n);  
    vector vec2(n);
    vector vec1(vec);   
    cout<<vec<<endl;
    cout<<vec1<<endl;

    return 0;
}

Which give no error output

James Adkison
  • 9,412
  • 2
  • 29
  • 43

2 Answers2

3

Your code causes undefined behaviour. When your code causes undefined behaviour, anything can happen. You should not expect any particular symptom, such as a crash or a lack of crash.

Your code causes undefined behaviour due to this section:

array = new int[0]; 
this->num=n;    
for ( int i=0; i<n; i++)
    array[i]=i;

When n > 0, you write out of bounds of the allocated space.

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365
  • I don't think that is the issue. I have to fetch elements in array equivalent to "n". Code is working fine, I am not understanding why double free or corruption error not thrown in second case. – arpit desai Mar 13 '16 at 00:11
  • 1
    @arpitdesai you cannot fetch `n` elements from an array of size `0` – M.M Mar 13 '16 at 00:27
2

One glaring issue is that your vector class lacks a user-defined copy constructor. When you do this in main:

vector vec1(vec);  

You are making a shallow copy (copying the pointer values). You will see that when the destructor of vector is called at the end of main for both of your vector objects:

~vector()
{
    delete [] array; // <-- Same pointer value being deleted twice
    cout<<"Base class Dest"<<endl;
}

This results in delete being called on the same array value twice when main exits. This is a double-delete error.

You need to implement a user-defined copy constructor and assignment operator to allow proper copying of your vector class. Read up on the the rule of 3 to ensure that copying the object doesn't cause memory corruption.

Community
  • 1
  • 1
PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45