Mediocre Gopher
Mediocre Gopher

Reputation: 2304

C++ array contents changing in between function calls

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() {
        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
0

Printing the array============
134513919
3221174380
0
0

I'm sure it's something simple that I'm missing, but why is this happening?

Upvotes: 1

Views: 119

Answers (3)

John Dibling
John Dibling

Reputation: 101506

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.

Upvotes: 2

Andy Finkenstadt
Andy Finkenstadt

Reputation: 3587

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.

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168876

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.

Upvotes: 7

Related Questions