1

I'm implementing a class (or rather a Baseclass, and classes inherit from it), which holds a Integer. Now I have the problem, that I only can return the pointer to the value once.:

Inte foo =  Inte(5);
cout << foo.getValue() << endl; // 5
foo.setValue(10);
cout << foo.getValue() << endl; // 10   
cout << foo.getValue() << endl; // 4199696

The getValue function doesn't do anything, besides returning the pointer, I have no Idea why it returns 4199696 after the first getValue().

Here my class:

class Object {

public:
    virtual int getValue() = 0;
    virtual void setValue(int *pointer) = 0;
    virtual string toString() = 0;

};


class Inte : public Object {
private:
    int* value;
public:
        Inte (int *val){
            value = val;
        }

        Inte (int val){
            int a = val;
            value = &val;
        }

        virtual int getValue(){
            return *value;
        };

        virtual void setValue(int *pointer){
            value = pointer;
        };

        virtual void setValue(int val){
            int a = val;
            value = &val;
        };

        virtual string toString(){
            stringstream ss;
            string s;
            ss << value;
            ss >> s;
            return s;
        };
};
pharno
  • 13
  • 3

1 Answers1

2
virtual void setValue(int val){
    int a = val;
    value = &val;
};

In this function you store the address of a local variable (val). This address will become invalid once this function exits, making any attempt to dereference the pointer (which is what you do in getValue) that hold this address undefined behavior.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • thanks. but then why does it work for the first call of getValue()? and how exactly can I fix it? – pharno Jan 18 '12 at 14:18
  • @pharno: Undefined behavior means that anything can happen. This includes that it works once, twice or more but at some point simply fails for no apparent reason. To fix it you have to create a new `int`-object dynamically: `value = new int(val)` - note that this introduces a host of new problems, as you have now entered the world of manual resource management. – Björn Pollex Jan 18 '12 at 14:24
  • "undefined behaviour" means that neither the compiler nor the language no longer care about what your program does or why it does it. Can be any reason for results you see, really, starting with random data in the address space of your program before it was loaded into memory. – bronekk Jan 18 '12 at 14:30