int *ip = new int[10];
for (int i = 0; i<10; i++)
*(ip+i) = i;
myfun(ip); // assume that myfun takes an argument of
// type int* and returns no result
delete [] ip;
The above code is a small segment of a test function that I am trying to use to learn about the stack and the heap.
I am not fully sure what the correct sequence is.
This is what I have thus far:
delete []ip;
removes the memory allocated on the heap to the ip pointer. The pointer that got passed through to myFun now points to nothing.Would someone be able to clarify if I am correct or not and correct me where I went wrong? Also if I attempted to carry on using ip after that would it just point to nothing ?
The sequence is correct except one point:
The delete []ip; removes the memory allocated on the heap to the ip pointer. The pointer that got passed through to myFun now points to nothing.
The pointer doesn't point to 'nothing' (i.e. isn't set to nullptr
or 0
after freeing the memory). It just points to the same location which is now freed memory (i.e. memory marked as freed by the application and that can no longer be safely accessed). Accessing memory through that pointer would trigger undefined behavior.
One last notice: myfun
might take the pointer by value or by reference. There are differences but your sentence would still be valid.
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