DEV Community

dinhluanbmt
dinhluanbmt

Posted on • Edited on

C++ Assignment operator vs _BLOCK_TYPE_IS_VALID

I have been using C++ for a long time, but I didn't pay much attention to the assignment operator and copy constructor until I encountered the "_BLOCK_TYPE_IS_VALID" error.
It took me several hours of googling to figure out the reason.
with this code:

class A {
    int* val;
public:
    A(int v) {
        val = new int(v);
    }
    ~A() {
        delete val;
    };
    A test() {
        A a(2);
        A b(3);
        a = b;// assignment operator
        return a;
    }
Enter fullscreen mode Exit fullscreen mode

we got the "_BLOCK_TYPE_IS_VALID" because when the class does not contain any pointers, the default assignment provided by Compiler is sufficient even it just performs a shadow copy.
but dealing with classes that contain pointers we can get _BLOCK_TYPE_IS_VALID(pHead->nBlockUse).
This error often occurs in Visual Studio when memory corruption or invalid memory access is encountered.
Similarly, in a Linux environment, you may encounter dump values or other exceptions.

so do not forget to define our own assignment operator.

class A{
int* val;
public:
  A(int v){
   val = new int(v);
 }
// assignment operator
 A& operator=(const A& obj){
   *val = *obj.val;
 }
~A(){ delete val;)
};
A test(){
 A a(2);
 A b(3);
 a = b;// assignment operator called
 return a; // copy constructor ??
}
Enter fullscreen mode Exit fullscreen mode

but still we got error?. because the return a; make a copy of a before return.
so we also need our own copy constructor
and this code will work without error:

class A{
int* val;
public:
  A(int v){
   val = new int(v);
 }
// assignment operator
 A& operator=(const A& obj){
   *val = *obj.val;
 }
//copy constructor
A(const A& obj){
 if(val) delete val;
 val = new int(*obj.val);
}
~A(){ delete val;)
};
A test(){
 A a(2);
 A b(3);
 a = b;// assignment operator called
 return a; // copy constructor ??
}
Enter fullscreen mode Exit fullscreen mode

Do your career a favor. Join DEV. (The website you're on right now)

It takes one minute and it's free.

Get started

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay