0
votes

I meet a memory leak problem and the minimum code as follows. My compiler is VS2008.

//haar.h
#include "stdio.h"
#include "stdlib.h"

class HaarClass
{
public:

    HaarClass(void);
    ~HaarClass(void);

    void Memory_Leak_Test();

private:
    long* feature_vector_;
};


HaarClass::HaarClass(void)
{
    feature_vector_ = NULL;
}

HaarClass::~HaarClass(void)
{
    if (feature_vector_ != NULL) {
        delete[] feature_vector_;
    }
}

void HaarClass::Memory_Leak_Test(){

    if (feature_vector_!=NULL) {
        delete[] feature_vector_; 
    }

    for (int i=0; i<10; i++)
    {
        feature_vector_ = new long[100];

        if (feature_vector_!=NULL) {
            delete[] feature_vector_; 
        }

    }

}

And the main file is

//main.cpp
#include <cstdio>
#include "haar.h"  

int main()
{
    HaarClass a;
    a.Memory_Leak_Test();

    return 0;
}

And the error or alert is

_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));

in dbgdel.cpp Line: 52.

Therefore, what's the error? Thanks.

1
The code that's shown in this question fails to meet the requirements of a minimal reproducible example. Unless this question gets edited, and a minimal reproducible example is provided, no answer will be possible. - Sam Varshavchik
if (feature_vector_!=NULL) -- What compiler are you using? If new[] fails, a std::bad_alloc exception is thrown, and not a NULL is returned. - PaulMcKenzie
Please post a Minimal, Complete, and Verifiable example. What is the purpose of the first if (feature_vector_!=NULL) { delete[] feature_vector_; }? is feature_vector_ initialized to NULL or pointer to buffer allocated and not deleted properly before calling this function? - MikeCAT
@Lee -- You seem to be under the impression that wherever the assert occurs is where the problem starts. That is not the case. That's why you need to show us the minimal reproducible example we've been asking for. You could be doing all sorts of things before this code is executed that could cause the error. - PaulMcKenzie
You're writing to memory outside the block that's been allocated, most likely before it (e.g. feature_vector_[-1]). It's detected in the destructor for feature_class when it tries to delete the allocated pointers. You're not NULLing out feature_vector_ after you delete it, so this might also be due to a double free (not sure if VS detects that differently). - 1201ProgramAlarm

1 Answers

0
votes

When you delete the pointer in your Memory_Leak_Test you do not set the pointer to NULL so your destructor will try to delete it again

void HaarClass::Memory_Leak_Test(){

    if (feature_vector_!=NULL) {
        delete[] feature_vector_; 
    }

    for (int i=0; i<10; i++)
    {
        feature_vector_ = new long[100];

        if (feature_vector_!=NULL) {
            delete[] feature_vector_; 
            feature_vector = NULL;    // <<-----
        }

    }

}