Home > Mobile >  valgrind profiling run crashes when calling constructors
valgrind profiling run crashes when calling constructors

Time:05-11

I've got this weird issue when using valgrind which confuses me alot. im running on ubuntu18.04, c 17, valgrind version 3.13.0

consider this struct:

struct KelvinLine {
    float m;
    float b;
    float epsilon;

    KelvinLine() {
        m = 0;
        b = 0;
        epsilon = 0;
    }
};

my test main looks something like this:

int main(){
    auto arrLen = 10;
    KelvinLine* kelvinArray = new KelvinLine[arrLen];
    
    delete kelvinArray;
    return 0;

}

when running it without valgrind everything is ok, but once running with valgrind it crashes it with unhandled instruction error, if instead of new i use malloc (with the proper size of the struct array that i wanted) it continues its run like normal. has anyone dealt with this issue before? thanks

Edit: fixed this issue by disabling AVX512F in my cmake

CodePudding user response:

The problem is that you're deallocating the memory using incorrect delete expression leading to undefined behaivor. Since you've used the array form of new expression, you must use the corresponding array form of delete expression as well:

//-----vv------------->use array form of delete expression
delete []kelvinArray;

CodePudding user response:

Whilst mixing delete and delete [] is UB, in cases like this (almost a POD struct) then it is likely to be harmless and never cause a crash.

The main difference between these two operators is that the array form will call the destructor on each element whilst the scalar form will only call it once (the first element if it is an array). That can potentially result in a resource leak. After calling the destructor, the memory for the instance/array gets freed. At least for the two implementations that I'm somewhat familiar with (llvm and GCC) that just means a call to free().

Since this struct has no user-defined destructor the two forms of operator delete are essentially equivalent.

That said, this isn't safe to assume in general and there is no reason not to call the correct operator delete [].

  • Related