Scope of local variables

Inspect the following code. Convince yourself that the expected output should be \fbox{\tt 0 1 2 3 4} . Compile and test the code. The output is unpredictable (may be similar to
\fbox{\tt 134524936 134524968
134524952 134524984 134525024} depending on the machine and circumstances). How do you explain this bug? How can you fix it?


#include<iostream>
#include<vector>

class ValueContainer {
public:
  ValueContainer() : theInt(0) { }
  ~ValueContainer() { }
  void set(int* t) {
    theInt = t;
  }
  int get(void) {
    return *theInt;
  }
private:
  int* theInt;
};

ValueContainer* createContainer(int i) {
  ValueContainer* ret = new ValueContainer;
  ret->set(&i);
  return ret;
}

const int vecSize = 5;
int main(int argc, char** argv) {
  using namespace std;
  vector<ValueContainer*> value;
  for(int i = 0; i < vecSize; i++) {
    value.push_back(createContainer(i));
  }
  for(int i = 0; i < vecSize; i++) {
    cout << value[i]->get() << " ";
  }  
  cout << endl;
  for(int i = 0; i < vecSize; i++) {
    delete value[i];
  }
  return 0;
}



Subsections

Leo Liberti 2008-01-12