I am trying to understand the new operator more closely. I do understand the fact that it allocated memory from the heap and returns a pointer to the memory. My question is that once I get the pointer and use it to store another pointer to another declared variable, how does the value copy or the value pointed to by happen? So for instance
i declare a variable
int x = 4;
and say
int* ptr = new int;
ptr = &x;
ptr points a chunk of memory from the heap. x is defined in a stack owning a separate chunk of memory. ptr and the address of x are the same. If I delete ptr, x is still valid as it still exists in the memory. When I say *ptr, I am looking for the value pointed to by ptr, which in this case is 4. My question is that 4, where does that reside. Does it live in two separate chunks of memory. One is represented by x and other I just got from new. How does the process happen? How does 4 get transmitted across the two chunks, or I am missing sthg? Please help.
Also when I say ptr = &x, is that a bitwise copy. In other words, do I forever loose the memory I just got access to through the heap?
int* ptr = new int;
ptr = &x;
ptr points a chunk of memory from the heap
No, it doesn't. After the assignment, it points at the address of variable x, which has automatic storage. You have lost the handle to the dynamically allocated int initially pointed at by ptr, so you can no longer delete it. 4 does not get transmitted across any "chunks" of memory. When you de-reference, ptr, you get the variable referred to by x, which holds the value 4.
Try this example:
#include <iostream>
int main()
{
int x = 4;
int* ptr = new int;
ptr = &x; // lose handle on dynamically allocated int: MEMORY LEAK
std::cout << (*ptr) << "\n";
x += 1;
std::cout << (*ptr) << "\n";
(*ptr) += 1;
std::cout << x << "\n";
}
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