Search code examples
c++17placement-newconstructor-overloading

C++ using placement new causes segmentation fault in constructor


please find below code. In this code, when I use "placement new", the I see segmentation fault in constructor, I am not sure why it is causing this, since I can create normal objects. Also, if I use new operator, the code works. Issue is only with placement new. Can someone help me understand this behavior?

#include<iostream>
#include<string>

using namespace std;
template<typename T=int>
class LessThan{
    public:
    LessThan(T x):mem(x){}
    bool operator()(T x){
        return x < mem;
    }

    private:
    T mem;
};

int main(){
    LessThan a(9);
    cout<<"less than 9: "<<a(10)<<endl;
    cout<<"less than 9: "<<a(8)<<endl;
    LessThan<int>* b = nullptr;// = new LessThan(11);
    new(b) LessThan<int>(11);
    if(b == nullptr){
        cout<<"b is null..."<<endl;
    }
    cout<<"less than 11: "<<(*b)(12)<<endl;
    cout<<"less than 11: "<<(*b)(8)<<endl;
    return 0;
}

Solution

  • LessThan<int>* b = nullptr;// = new LessThan(11);
    new(b) LessThan<int>(11);
    

    I'm not sure what kind of trick you are trying to achieve when passing a nullptr into new operator, but when using the placement new operator, you are supposed to allocate enough space (and align it properly) to fit in an instance of your class. The pointer should point to the allocated memory, not just an empty pointer of the given class:

    char memory[sizeof(LessThan<int>)];
    new(memory) LessThan<int>(11);