gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

DS development > Corrupted memory

#166124 - Echo49 - Fri Jan 30, 2009 12:46 pm

I have code similar to the following:
Code:
class Object
{
    public:
        Object(int value);
        int getValue() { return mValue; }
    protected:
        int mValue;
};

Object::Object(int value)
{
    mValue = value;
    iprintf("%i", mValue);
}

int main()
{
    Object o(100);
    iprintf("%i", o.getValue());
}

The first iprintf outputs the correct value as expected, but the one after the constructor returns is a totally different value. Any idea what is causing this - some sort of stack corruption?

#166126 - hacker013 - Fri Jan 30, 2009 6:04 pm

i think this should work:

Code:

class Object
{
    public:
        Object(int value);
        int getValue();
    protected:
        int mValue;
};

Object::Object(int value)
{
    mValue = value;
    iprintf("%i", mValue);
}

int Object::getValue()
{
return mValue;
}

int main()
{
    Object o(100);
    iprintf("%i", o.getValue());
}

_________________
Website / Blog

Let the nds be with you.

#166129 - Echo49 - Fri Jan 30, 2009 9:45 pm

I found my mistake; My code actually uses an object rather than an int in the class, and I foolishly declared an object on the stack in the constructor to assign to it. So, as soon as the constructor returned, the pointer was no longer valid. That should teach me to code at 1am ==