I wanted to create an array of a certain class but its size was not determined until run time. Therefore I had to of course use a pointer. Now because it was always good practice to initialize a pointer to NULL, I did so and I passed this initialized pointer to a function. This function would then new the pointer inside, seemed OK but this made the program crash.
I used the function AllocateArray1in the gist. Why did it crash?
The pointer is passed by value and when the function exits the pointer being passed is not quite initialized.
To verify this I used the test case 3 where I created an array, deleted it but didn't assign it back to NULL, this made sure that the pointer is still pointed to a certain memory address.
The works because although the memory is deallocated we can still access the values using raw pointers, although this might crash some times due to access violation.
The other option of course, which I used was to pass the pointer by reference. AllocateArray2 ensures that the same memory address is passed.
I used the function AllocateArray1in the gist. Why did it crash?
The pointer is passed by value and when the function exits the pointer being passed is not quite initialized.
To verify this I used the test case 3 where I created an array, deleted it but didn't assign it back to NULL, this made sure that the pointer is still pointed to a certain memory address.
The works because although the memory is deallocated we can still access the values using raw pointers, although this might crash some times due to access violation.
The other option of course, which I used was to pass the pointer by reference. AllocateArray2 ensures that the same memory address is passed.
Comments
Post a Comment