So I've been returning to the world of C/C++ after many years of working in Java/C# and Python. I've been a software engineer for the better part of 12 years so I'm familiar with value vs reference and design patterns, but this issue I've been seeing has made me scratch my head and question myself.
I've been following a primer guide to get myself back up to speed with C/C++, starting from the basics including pointers. I've been working on dynamic arrays and memory management. I know... I know... in production situations I'm better off using vectors, but this is for education and catching up. So on to the problem...
Here is sample code:
int main() {
int capacity = 1;
int size;
int * dynamicArray = CreateDynamicArray(capacity, size);
InsertElement(dynamicArray, 20, size, capacity);
ResizeDynamicArray(dynamicArray, size, capacity + 1);
delete[] dynamicArray
return 0;
}
int * CreateDynamicArray(int capacity, int& size){
size = 0;
cout << "Creating Dynamic Array of size: " << capacity << endl;
return new int[capacity];
}
void InsertElement(int* dynamicArray, int element, int& size, int& capacity){
dynamicArray[size] = element;
size++;
}
void ResizeDynamicArray(int* dynamicArray, int& size, int newCapacity){
int * temp = new int[newCapacity];
copy(dynamicArray, dynamicArray + size, temp);
delete[] dynamicArray;
dynamicArray = temp;
}
So here we are using the new/delete method of memory allocation (will move to alloc/free later if I need to). When I write this code all into the main function, meaning no other functions, everything works perfectly fine. But when I break the code into separate functions I get really weird behavior with the memory.
in ResizeDynamicArray()
I create the temp pointer and use std::copy
to move data into the resized array. I then delete the old pointer and then point to the new array. However, while watching the pointer and outing the value, after the function returns the pointer's reference value dynamicArray[0]
goes from 20 to some random value, as if the pointer was deleted. If I remove the delete[] dynamicArray
portion it doesn't have this issue.
So this leaves me thinking, why does deleting the old pointer affect the new address that I am now pointing to? Why does this behavior only happen when done within a function? How do I best avoid this?
Using double pointers int** dynamicArray
seems to avoid this issue, but I'm having a hard time understanding why as you have to deference back to the first pointer anyways.