Bob Sacamano
Bob Sacamano

Reputation: 439

Solving the "_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)" crash. C++

I have this simple piece of code:

    struct A {
        char* str;
        A() : str(NULL) {}
        ~A() { delete[] str; }
    };

    void bar(A a) {
        printf("%s", a.str);
    }

    int main() {    
        A b;
        b.str = _strdup("string");
        bar(b);
        return 0;
    }

which causes the assertion failure. The source of the problem as far as I can gather is the c'tor\d'tor. Please help!

Upvotes: 1

Views: 224

Answers (2)

user4842163
user4842163

Reputation:

You need a copy constructor, otherwise your str field will get shallow copied when calling bar, and the destructors of both instances of A will try to free the same memory twice. Also _strdup uses malloc, so you should match it with a call to free rather than operator delete[].

For C++, you can avoid all these memory management issues just using std::string or even std::vector<char>

Example:

struct A 
{
    char* str;
    A(): str(NULL) {}

    // Copy Ctor
    A(const A& other): str(strdup(other.str)) {}

    // Copy Assignment
    A& operator=(const A& other)
    {
         if (this != &other)
         {
              free(str);
              str = strdup(other.str);
         }
         return *this;
    }

    // Dtor
    ~A() 
    {
        free(str);
    }
};

Or, much simpler:

#include <iostream>
#include <string>

using namespace std;

struct A 
{
    string str;
};

void bar(const A& a) {
    cout << a.str << endl;
}

int main() {    
    A b;
    b.str = "string";
    bar(b);
}

Upvotes: 4

EvilTeach
EvilTeach

Reputation: 28882

strdup uses malloc under the covers.

Use free to free it instead of delete[].

  • malloc/calloc -> free
  • new -> delete
  • new[] -> delete[]

Upvotes: 2

Related Questions