Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make variable truly read-only in C++?

Tags:

c++

constants

By using the const qualifier a variable is supposed to be made read-only. As an example, an int marked const cannot be assigned to:

const int number = 5; //fine to initialize
number = 3; //error, number is const

At first glance it looks like this makes it impossible to modify the contents of number. Unfortunately, actually it can be done. As an example const_cast could be used (*const_cast<int*>(&number) = 3). This is undefined behavior, but this doesn't guarantee that number does not actually get modified. It could cause the program to crash, but it could also simply modify the value and continue.

Is it possible to make it actualy impossible to modify a variable?

A possible need for this might be security concerns. It might need to be of highest importance that some very valuable data must not be changed or that a piece of data being sent must not be modified.

like image 565
janekb04 Avatar asked Dec 30 '22 23:12

janekb04


1 Answers

No, this is not the concern of a programming language. Any "access" protection is only superficial and only exists at compile-time.

Memory of a computer can always be modified at runtime if you have the corresponding rights. Your OS might provide you with facilities to secure pages of memory though, e.g VirtualProtect() under Windows.

(Notice that an "attacker" could use the same facilities to restore the access if he has the privilege to do so)

Also I assume that there might be hardware solutions for this.

There is also the option of encrypting the data in question. Yet it appears to be a chicken-and-egg situation as the private key for the encryption and decryption has to be stored somewhere in memory as well (with a software-only solution).

like image 171
Sebastian Hoffmann Avatar answered Jan 12 '23 01:01

Sebastian Hoffmann