Anton Serov
Anton Serov

Reputation: 301

Access violation on ending the main function scope but only with Visual Studio 2019 and gcc

UPD: My main goal is to create some sort of a wrapper around the SimpleStructBase structure. The wrapper that could manage resources that are currently unmanaged and represented in SimpleStructBase as raw pointers (unfortunately, another restriction is that I cannot change the design of SimpleStructBase, I would have just switched everything to smart pointers). Ideally, the wrapper should be inherited from the base structure.

I don't understand why I'm getting the access violation on reading location on leaving the main function scope in this program:

#include <iostream>
#include <string>

struct SimpleStructBase
{
    int* intPointer;
};

struct MemHolder
{
    SimpleStructBase& params;
    MemHolder(SimpleStructBase& dist) : params(dist)
    {
        params.intPointer = new int(*dist.intPointer);
    }

    ~MemHolder()
    {
        delete params.intPointer;
    }
};

struct SimpleStructMng : SimpleStructBase
{
protected:
    SimpleStructMng(SimpleStructBase& params) : SimpleStructBase(params) {}
    std::shared_ptr<MemHolder> mem;

public:
    ~SimpleStructMng() {}

    static SimpleStructMng CreateStruct(SimpleStructBase& params)
    {
        SimpleStructMng ret = { params };
        ret.mem = std::make_shared<MemHolder>(ret); //This thing crashes
        return ret;
    }
};

int main() {
    SimpleStructBase objBase;
    objBase.intPointer = new int(42);

    SimpleStructMng objMng = SimpleStructMng::CreateStruct(objBase);

    std::cout << "Base object: " << *objBase.intPointer << "\n";
    std::cout << "Managed object: " << *objMng.intPointer << "\n";

    return 0;
}

In the end of the CreateStruct, MSVC 2019 compiler (as well as gcc) for some reason first clears the object ret (also removing the only reference in ret.mem smart pointer) and then returns the object from the function. Of course, ret.mem becomes unavailable. Interesting that MSVC 2022 doesn't do that and everything works fine.

How can I change the program so it doesn't crash even in MSVC 2019/gcc? The only restriction is that the SimpleStructBase structure should keep unchanged.

Upvotes: 0

Views: 123

Answers (0)

Related Questions