Example code:
#include <stdio.h>
class compArray {
public:
unsigned int* myArr; //The array
compArray() {
unsigned int temp[4];
for (unsigned int i=0;i<4;i++) {
temp[i] = 0;
}
myArr = temp;
print_arr(myArr);
}
void set() {开发者_JS百科
print_arr(myArr);
}
static void print_arr(unsigned int* arr) {
printf("Printing the array============\n");
for (unsigned int i=0;i<4;i++) {
printf("%u\n",arr[i]);
}
printf("\n");
}
};
main() {
compArray test;
test.set();
}
The output:
Printing the array============
0 0 0 0Printing the array============
134513919 3221174380 0 0
I'm sure it's something simple that I'm missing, but why is this happening?
In your constructor, you have these two lines:
unsigned int temp[4];
...
myArr = temp;
You set your member variable pointer myArr
equal to the address of your local variable temp
. But, temp
goes out of scope and is destroyed as soon as you return from the constructor.
After that, myArr
refers to storage that is no longer allocated, and exhibits undefined behavior.
Because this isn't an array:
unsigned int* myArr; //The array
...it's a pointer. A pointer and an array are different things entirely. Arrays can be decomposed in to pointers in some cases, but they still aren't the same thing.
This is the array:
unsigned int temp[4];
...and it's falling off the stack at the end of the function.
When you do this:
myArr = temp;
...you aren't copying the contents of the array, you're just copying the address of the first element of the array. When the function in which temp
is allocated exits, the array itself falls off the stack, and myArr
becomes a wild pointer, pointing to uninitialized memory.
unsigned int temp[4];
for (unsigned int i=0;i<4;i++) {
temp[i] = 0;
}
myArr = temp; // OOPS!
You initialized myArr to a value that was on the stack. When the constructor finished executing, the C++ Compiler was free to reuse that space, and, it did.
精彩评论