+ 3
"Default" Value for Dangling Pointers
Would the outputs from line 2 and line 6 below always be the same on each run? I guess the more general thing to ask is if the value placed in the memory address is the same value after assigning a value to that address and then clearing that assigned value? From my understanding it would be because the compiler would pick something to place there after the program is built, then overwrite it with the value chosen in the program, then remove that chosen value. The address would then contain the original value chosen by the compiler at the start of the run. 1. int * p = new int; 2. cout << *p << endl; 3. *p = 12; 4. cout << *p << endl; 5. delete p; 6. cout << *p;
6 Respostas
+ 3
Your OS gives your program memory when it needs it (usually in 4kb chunks), but there is no special cleaning up procedure so line 2 will just print whatever the program that was running before yours has written there.
Line 6 will print 12 if you're lucky, but when you delete your pointer you no longer have control over that memory spot. The OS or your program might just aswell have repurposed that memory, in which case it won't print anything, but crash your program (because the program/OS is saying "you can't have it, that isn't yours").
I hope that made sense!
+ 1
Maybe I wasn't clear enough then!
The compiler doesn't assign a "garbage value" to pointers, and no pointers are ever "cleared". Anything that is written to a memory location stays there until something else overwrites it (or possibly you reboot your computer).
`new` and `delete` are more about access control than anything else. Every program on your computer shares the same 8 gigabytes or so of RAM with any other program, so what looks like garbage to you might just have been some useful calculation made by the program running before yours.
0
I don't think you're understanding my question. I'm asking if the "garbage number" the compiler gives the address at the start of running will be the same number that is in the address after the pointer is cleared. I wouldn't code something like this; I'm just asking if that is what would happen.
0
@Schindlabua I was talking more about the other person's comment about calling the output right after allocating memory. I am trying to check the value x written at the address before the assignment statement, which would give it a value y. I want to know what value would be there after the address is freed from y (if it is the same as x or if it is different and why). I'm sorry if this is a foolish question, but I'm trying to understand the "back" stuff more.
0
Nono it's a great question! I hope I anwered it ok?
Before the assignment the pointer will contain garbage, after deleting it'll still contain what you assigned to it (12) until the memory where the pointer pointed to is used for something else.