3

(Relevant to this question.)

I have a base class Base and two derived classes, Der1 and Der2. (See linked question for basic implementation. Each has a number of public properties as well.) In my program I create an array of Base like this:

Base *array[10];
int count = 0; // program-wide count of how many objects are in the array

Then later on I fill it with instances of Der1 and Der2 as follows:

Der1 d = Der1();
d.x = 0; // Filling in public properties
d.y = 1;
d.z = 3;
array[count] = &d;
count++;

Near-identical code is used for Der2.

Much later, I use the array to call on functions defined in those classes:

int result = array[i]->SomeFunction(x, y);

My code compiles fine, but when I try to run it I get "Unhandled exception at 0x00232d60 in program.exe: 0xC000005: Access violation reading location 0x04064560."

When I take a look at the object in the array I'm trying to access, all of the properties' values are 0.0000 instead of what they're supposed to be. There are also two double-type arrays and it looks like the last few elements are uninitialized ("1.572398880752e-311#DEN" or "-9.2559631349317831e+061" or similar).

I've been doing .NET too long and have forgotten a lot of what I knew about pointers, which I'm assuming is the source of my problem... Any suggestions on how I can fix this error?

Community
  • 1
  • 1
Andrew
  • 4,953
  • 15
  • 40
  • 58
  • 1
    I am totally lost on how `array[2]` up to `array[9]` are filled in. And on what value `i` has. Probably, you are too. – xtofl Feb 19 '11 at 17:50
  • They aren't filled in, but my program ensures that they are never accessed unless they ARE filled in. – Andrew Feb 19 '11 at 18:04

4 Answers4

6

You filled the array with pointers to local variables. Those are only valid as long as the original local variable is still valid. Most likely, the objects you are trying to access simply went out of scope. Try allocating them on the heap and see if that solves the problem.

Puppy
  • 144,682
  • 38
  • 256
  • 465
4
Der1 d = Der1();

constructs a instance of Der1 on the stack. If d goes out of scope before you call SomeFunction you get a access violation. You need to construct Der1 on the heap by using new.

Der1* d = new Der1();

You need to delete the d instance if you don't need it anymore or at the end of the program:

delete d;
Fox32
  • 13,126
  • 9
  • 50
  • 71
2

After the following:

Der1 d = Der1();
...
array[count] = &d;

Your object d will be destroyed as soon is the above scope is over. This means you cannot try to access then later with something like this:

array[i]->SomeFunction(x, y);

Since the object previously reference by the pointer in that position is now gone.

Leandro T. C. Melo
  • 3,974
  • 22
  • 22
1
int result = array[i]->SomeFunction(x, y);

Make sure i is less than 10, and greater or equal to 0.

Nawaz
  • 353,942
  • 115
  • 666
  • 851