user2551229
user2551229

Reputation: 375

Debug Assertion Failed in such simple example

main.cpp

#include <iostream>
#include "Simple.h"

using namespace std;

int main()
{
    Simple s;
    s = Simple();
}

Simple.cpp

#include "Simple.h"

Simple::Simple(void)
{
    ptr = new int[10];
}


Simple::~Simple(void)
{
    delete [] ptr;
}

Simple.h

#pragma once
class Simple
{
public:
    Simple(void);
    ~Simple(void);

private:
    int* ptr;
};

When I run main.cpp, program stops and return an error:

Microsoft Visual C++ Debug Library Debug Assertion Failed!

Program: ...ts\Visual Studio 2010 C++\simple error\Debug\simple error.exe File: f:\dd\vctools\crt_bld\self_x86\crt\src\dbgdel.cpp Line: 52

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.

(Press Retry to debug the application)

Why it happens in such common example?

Upvotes: 0

Views: 1492

Answers (1)

Stuart Golodetz
Stuart Golodetz

Reputation: 20656

You need to add a copy constructor and assignment operator. At the moment, your line

s = Simple();

does the following:

  • Creates a temporary Simple, allocating memory for its pointer to point to.
  • Assigns it to s, which simply copies the pointer across from the temporary.
  • Destroys the temporary again, deallocating the memory now pointed to by both the pointer in the temporary and the pointer in s.

At this point, the pointer in s points to deallocated memory. When s goes out of scope, the Simple destructor tries to deallocate the memory s's pointer points to again, and undefined behaviour occurs (in your case, your program crashes).

Upvotes: 3

Related Questions