Dead Beetle
Dead Beetle

Reputation: 111

Can you dereference an integer literal?

Is it possible to use, for example:

int x = *776

to get a value from a specific memory location? Or do you absolutely have to use:

int ref = 776;
int x = *ref;

Upvotes: 3

Views: 3637

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Sure, memory addresses can be expressed from certain integer literals, such as

int* ptr = reinterpret_cast<int*>(776);

and dereferencing these as

int value = *ptr;

is legit. So is

int value = *reinterpret_cast<int*>(776);

If you can actually access this hard coded memory address totally depends on your target environment.

In most cases the operating system will prevent you from accessing arbitrary memory addresses and quit you with a SEGFAULT or alike.


Or do you absolutely have to use:

int ref = 776;
int x = *ref;

You cannot use that code, that's completely nonsensical and won't compile.

What you probably meant was

int* ref = reinterpret_cast<int*>(776);
int x = *ref;

and as mentioned above

int x = *reinterpret_cast<int*>(776);

is legit as well.

Upvotes: 3

callyalater
callyalater

Reputation: 3102

In short, no. You cannot say int x = *776; because 776 is an integer literal and interpreted as an int not an int*.

The longer answer is that you (probably) don't want to do this (the concept of explicitly dereferencing a specific memory address) because (1) it is not portable, (2) makes your code very fragile, and (3) doesn't really do what you want it to do.

There are many way to access memory on a computer, but they are not mutually compatible. The most basic way is called direct addressing. This is where each place in memory has an address and when you say "Go to location 0x308" it goes to that cell in physical memory. This can be very dangerous because you can access regions of memory that the OS or BIOS is using. It also prevents you from (easily) running more than one program on your computer.

Other ways of indirect accessing memory is relative (offset) addressing and segmented addressing. These have a layer of protection between the addresses you are using and the physical layout and can prevent you from accessing memory you are not supposed to. Generally speaking, this is why you get segfaults.

If you write code that is accessing memory at a specific location, the OS may screw everything up for you, or you could break your microcontroller.

So though you could do int x = *((int*)776);, you probably don't want to do that and it will most likely segfault.

Upvotes: 2

Related Questions