D
Denis Remezov
John said:Hi all,
In my code, pointer changes unexpectedly. Below is the description of
the problem:
void class1::function1(){
class2 *r1;
class2 *rr[10];
r1 = new class2;
printf("r1_1: %d\n", r1);
function2(rr);
for(int i=0; rr!=NULL; i++){
printf("r1_2: %d\n", r1);
......
}
printf("r1_3: %d\n", r1);
}
The above code shows the structure of my code.
I define two classes.
The function2() is used to bring back an array of pointers, rr[], of
which the last element is NULL to indicate the end of the array.
There are 100 objects of class1. The strange thing is that at a
particular time when one object executes function1(), I get the
following output:
r1_1: some value, like 3563246.
r1_2: 0
r1_2: 0
r1_2: 0
r1_2: 0
r1_2: 0
r1_3: 0
But the pointer r1 should not change. r1_1, r1_2 and r1_3 should be
the same non-zero value.
This problem only happens once, during the execution of the code.
What is the problem?
Impossible to say for sure without seeing function2().
The obvious guess is that function2(rr) overwrites the content of r1
(the pointer) when it initialises the rr array (it's very easy if r1
and rr live on the stack, r1 immediately following or preceding the
rr array). You are lucky you didn't overwrite function1's return
address. Look for any indicies being out of range while accessing
rr in function2().
How does function2() know how many elements there are in the array?
It shouldn't just rely on a magic number. If you insist on using an
array, at least make its size known explicitly, it will be easier to
avoid problems like this that way. Better yet, use an std::vector
instead and avoid tricks like storing a NULL to indicate the end
of a sequence.
Denis