Search code examples
c++vectorstackallocation

C++ modifying Object data constructed with stack arguments


Guys I can't seem to do simple modification of a container object member stored in a vector. This member is an object itself. Both the container and its member are allocated on the stack. I think it is trying to deallocate a stack variable of the original name of the device when assigning a new one.

Please give me a clue on how to fix this while keeping variables allocated on the stack.

class Device{
    public:
        Device(string name):m_name(name)
        {}
        string getName(){
            return m_name;
        }
        string setName(string  newName){
            m_name = newName;
        }
        
    private:
        string m_name;
         
};

Then there is a Server that contains Devices:

class Server
{
    public:
        Device & getDevice(int i)
        {
            return devices.at(i);
        }
        void addDevice(Device && dev)
        {
            devices.push_back(dev);
        }
    private:
        vector<Device> devices;
};

Here is how I test:

int main()
{
    Server s{};
    
    s.addDevice(Device{"ONE"});
    s.addDevice(Device{"TWO"});
    s.addDevice(Device{"THREE"});
    
    cout<<s.getDevice(0).getName()<<endl;
    s.getDevice(0).setName("XXX");
    cout<<s.getDevice(0).getName()<<endl;
    return 0;
}

What I am getting out is :

ONE                                                                                                                                           
                                                                                                                                              
*** Error in `./a.out': double free or corruption (fasttop): 0x0000000000617c20 ***                                                           
Aborted (core dumped)   

Solution

  • You need to fix your setName method, is not returning anything and is marked to return a string.

    string setName(string  newName)
    {
         m_name = newName;
         return m_name; //this is missing in the original code
    }