Home > Back-end >  Is it possible to assign address value directly to a pointer?
Is it possible to assign address value directly to a pointer?

Time:06-07

I'm learning C from www.learncpp.com. The tutorials are good and I could ask the author myself by commenting but it takes some time to get a reply. So, here is something I'm confused in lesson 23.7 near the end of the lesson.

A warning about writing pointers to disk

While streaming variables to a file is quite easy, things become more complicated when you’re dealing with pointers. Remember that a pointer simply holds the address of the variable it is pointing to. Although it is possible to read and write addresses to disk, it is extremely dangerous to do so. This is because a variable’s address may differ from execution to execution. Consequently, although a variable may have lived at address 0x0012FF7C when you wrote that address to disk, it may not live there any more when you read that address back in!

For example, let’s say you had an integer named nValue that lived at address 0x0012FF7C. You assigned nValue the value 5. You also declared a pointer named *pnValue that points to nValue. pnValue holds nValue’s address of 0x0012FF7C. You want to save these for later, so you write the value 5 and the address 0x0012FF7C to disk.

A few weeks later, you run the program again and read these values back from disk. You read the value 5 into another variable named nValue, which lives at 0x0012FF78. You read the address 0x0012FF7C into a new pointer named *pnValue. Because pnValue now points to 0x0012FF7C when the nValue lives at 0x0012FF78, pnValue is no longer pointing to nValue, and trying to access pnValue will lead you into trouble.

It's written as if we could store an address like 0x0012ff78 and retrieve it directly back to a pointer. Hence the question, since I couldn't find an answer anywhere.

CodePudding user response:

Yes you can, and in C it looks something like:

auto ptr = reinterpret_cast<ptr_type>(0x0012FF7C);

Where ptr_type is a valid pointer type, like int* for example.


To add a bit more clarity to the problem outlined in the lesson:

Memory addresses are constantly being reclaimed and reused as required by the different programs running on a system.

When your program starts running, the OS keeps track of which memory addresses your program is allowed to access, and when your program ends, those memory address are reclaimed by the OS, for use by another process which might need it.

If you restart your program and attempt to modify or access (de-reference) the information stored at a particular address which your program did not explicitly request for, the OS will (should) detect this and may decide to end the program.

  • Related