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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With