3

I have a function that fills up a dynamic array by first putting values into a vector.

void fillArray(int*& arr) {
    vector<int> temp;
    for(int i = 0; i < 10; i++) {
        temp.push_back(i);
    }
    arr = &temp[0];
}

int main() {
    int* arr;
    fillArray(arr);
    for(int i = 0; i < 10; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}

Output:

0 1 2 3 4 5 6 7 8 9

Based on this answer, the code I'm using only creates a pointer to the vector's internal array - but said vector is destroyed after leaving the scope of the function. Why is it then that printing the array after the fact gives me the correct output?

According to the answers of this question, I should indeed be getting errors. So why does this work? [Runnable version]

Community
  • 1
  • 1
idlackage
  • 2,715
  • 8
  • 31
  • 52

3 Answers3

1

You just end up with undefined behaviour. The memory might be marked as free, but the previous contents may still be at that memory location. This is what you are seeing. The next allocation of memory may fill that space with garbage.

I have modified your example slightly by allocating another vector of int after the function exits, and now you see that there is trash in the printed vector . .

http://ideone.com/DLy1PF

int* v;
dothings(v); 
vector<int> temp = {1,2,3,2,1,2,3,12,3,1,2,3,1,23,1,2,3,1,23,1,2,3,1,3,12};
for(int i = 0; i < 10; i++) {
    cout << v[i] << endl;
}

Output: 12, 135065, 2, 3, 4, 5, 6, 7, 8, 9

learnvst
  • 15,455
  • 16
  • 74
  • 121
0

This is what called undefined behavior. System may or ay not give you the result as you expect!!

Steephen
  • 14,645
  • 7
  • 40
  • 47
0

This is undefined behaviour, and is the very definition of a dangling pointer error. Note that undefined does not always mean it will immediately return something incorrect or throw an exception - in this case, it could take some time for errors to occur in your data.

When a pointer is destroyed, the memory is not immediately freed or reset to 0x0000... - this would take time and resources on the system. Instead, the OS marks the memory as free, and will assign it again as more memory requests are made. Since you're testing immediately after creating the dangling pointer, the OS has not yet repurposed the memory, and the bits remain as they were made by the function. If you were to, say, run a dozen other funtions, you might see erroneous output instead, since the OS has given the memory to something else which is now making changes.

David
  • 10,458
  • 1
  • 28
  • 40