+ 4
using dangling pointers as a secret data access in C
let us say that i create a pointer and place a string on the address location, if i save the address location then leave the address as a dangling pointer. Can i reaccess the dangling pointer if i assign a new pointer to the previously saved address location and read the string again? i can try doing them myself but i might want some advice before placing a dangling pointer on my computer.
2 Answers
+ 5
And if you're saying what I think you're saying and you want to store information this way in between program runs then the answer is a hard no:
Firstly, we are talking about RAM here, which is constantly in use by different programs who constantly write things there. Also if the power goes out all the data is gone anyway.
Secondly and more importantly, the memory addresses you use aren't actual memory addresses. They are "virtual"âthere is a translation layer in between addresses and actual memory. If you read at location 12345 now and restart the program and do it again, you will have probably read from two different physical memory locations, even though the virtual address stayed the same.
(This is a thing because this way the operating system can better manage the hundreds of programs needing memory all the time and it can move things to your hard drive if RAM gets full. But let's not get too technical.
For this job you should just use files :P)
+ 4
"Dangling" means you have a pointer that points somewhere but you no longer own the memory.
foo* ptr = something();
free(ptr);
// ptr is now dangling
Who owns the memory then?
Either the C memory manager, which has the job of getting memory in larger chunks from your operating system and giving it out in smaller chunks to all your variables.
If it still has that block of memory you may be lucky and still be able to read what you wrote there.
More likely than not, the memory manager will have given that memory to some other part of your code and you will have overwritten what you wrote there. In this case you will get garbage if you try to read from `ptr`.
Also likely: The memory manager may have relinquished control of that block of memory back to the operating system, which will have given your memory away to another program entirely. In that case your program will crash if you try to read from `ptr`âthe operating system will prevent you from reading memory that isn't yours.