473,724 Members | 2,246 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is an address change possible by "deconstify/const_cast"?

I am interested to know if the pointer value for the memory address can
be changed by a compiler if the constness of the corresponding type is
cast away.

inline char* deconstify1(cha r const * X) { return (char*) X; }
inline char* deconstify2(cha r const * X) { return const_cast<char *>(X);
}

const char source [] = "Test";
char* alias1 = deconstify1(sou rce);
char* alias2 = deconstify2(sou rce);

if ((source != alias1) || (source != alias2) || (alias1 != alias2))
{ printf("unequal : %p %p %p", source, alias1, alias2); }

Can this happen on a current platform?
Does any tool try to copy the data to a read-only area to achieve any
protection?

Regards,
Markus

Jul 23 '05 #1
12 2413
Ma************@ web.de wrote:
I am interested to know if the pointer value for the memory address can
be changed by a compiler if the constness of the corresponding type is
cast away.

inline char* deconstify1(cha r const * X) { return (char*) X; }
inline char* deconstify2(cha r const * X) { return const_cast<char *>(X);
}

const char source [] = "Test";
char* alias1 = deconstify1(sou rce);
char* alias2 = deconstify2(sou rce);

if ((source != alias1) || (source != alias2) || (alias1 != alias2))
{ printf("unequal : %p %p %p", source, alias1, alias2); }

Can this happen on a current platform?
No. The result of a const_cast on a pointer must refer to the same object as
the original pointer.
Note that the result of writing to an object that was initially declared
const is undefined.
Does any tool try to copy the data to a read-only area to achieve any
protection?


Yes. There are also platforms where such data initially lives in read-only
memory.

Jul 23 '05 #2
Ma************@ web.de wrote:
I am interested to know if the pointer value for the memory address can
be changed by a compiler if the constness of the corresponding type is
cast away.


Not in C (I don't know about C++). Section 6.3.2.1
paragraph 2: "If the lvalue has qualified type, the value has
the unqualified version of the type of the lvalue; [...]" Thus,
the value of a const-qualified pointer to some object is equal to
the value of an unqualified pointer to the same object. It's
possible that the representation could be different (do not
mis-read 6.2.5/25 as prohibiting this), but `==' must hold.

--
Eric Sosman
es*****@acm-dot-org.invalid
Jul 23 '05 #3
Me
Ma************@ web.de wrote:
I am interested to know if the pointer value for the memory address can
be changed by a compiler if the constness of the corresponding type is
cast away.
The bits may change, but it's value can't. i.e. you can use the
equality/relational operators to compare it, but you can't use memcpy.
You can however use memmove/memcpy to copy the bits over though.
inline char* deconstify1(cha r const * X) { return (char*) X; }
inline char* deconstify2(cha r const * X) { return const_cast<char *>(X);
}
These two mean the exact same thing.
const char source [] = "Test";
char* alias1 = deconstify1(sou rce);
char* alias2 = deconstify2(sou rce);

if ((source != alias1) || (source != alias2) || (alias1 != alias2))
{ printf("unequal : %p %p %p", source, alias1, alias2); }
I think you meant && and not ||. Even with &&, this example will always
evaluate to true. Your example doesn't even answer what you really
mean. What you really meant was:

const char source [] = "Test";
const char *p1 = source;
char *p2 = deconstify1(sou rce);
const char *p3;

memcpy(&p3, &p2, sizeof(p2));

p1 == p3

And the answer is: yes, this is guaranteed to be true because
qualifiers only change the level of access in terms of the type system,
not the way the bits are interpreted in a pointer:

3.9.2/3 Pointers to cv-qualified and cv-unqualified versions (3.9.3) of
layout-compatible types shall have the same value representation and
alignment requirements (3.9).

^-- this is an even stronger guarantee about the representation being
the same

3.9.3/1 The cv-qualified or cv-unqualified versions of a type are
distinct types; however, they shall have the same representation and
alignment requirements (3.9).50)
3.9.3/1#50) The same representation and alignment requirements are
meant to imply interchangeabil ity as arguments to functions, return
values from functions, and members of unions.

^-- this is extra to say that even the top level const on pointers have
the same representation, so we can change "const char *p1" to "const
char * const p1" and it will still work.

Can this happen on a current platform?
Does any tool try to copy the data to a read-only area to achieve any
protection?


I don't understand what you're asking. Any const object[*] is allowed
to be stored in read only memory. You can cast away constness and read
from it, but any write to that storage location results in undefined
behavior.
[*] top level consts, i.e. "int * const var" is allowed to be stored in
read only memory but "const int *var" is not.

Jul 23 '05 #4
Me
Me wrote:
Ma************@ web.de wrote:
I am interested to know if the pointer value for the memory address can
be changed by a compiler if the constness of the corresponding type is
cast away.


The bits may change, but it's value can't. i.e. you can use the
equality/relational operators to compare it, but you can't use memcpy.


I meant memcmp.

Jul 23 '05 #5
> No. The result of a const_cast on a pointer must refer
to the same object as the original pointer.
Note that the result of writing to an object that was
initially declared const is undefined.


How do you think about the following code example?

struct context
{
long key;
char const * name;
} ctx;

if (ctx.name = (char*) strdup(source))
{
// The string is treated as a constant after the initial assignment.
ctx.key = rand();
printf("%li: %s", ctx.key, ctx.name);

// Release memory after processing
free(deconstify 1(ctx.name));
}

Regards,
Markus

Jul 23 '05 #6
[...]
Thus, the value of a const-qualified pointer to some object is
equal to the value of an unqualified pointer to the same object.
It's possible that the representation could be different
(do not mis-read 6.2.5/25 as prohibiting this), but '=='
must hold.


How can a representation be different and manage the same object here?
What is the difference that can be recognized by the relational
operators or the function "memcmp"?

Regards,
Markus

Jul 23 '05 #7
Ma************@ web.de wrote:
[...]
Thus, the value of a const-qualified pointer to some object is
equal to the value of an unqualified pointer to the same object.
It's possible that the representation could be different
(do not mis-read 6.2.5/25 as prohibiting this), but '=='
must hold.

How can a representation be different and manage the same object here?
What is the difference that can be recognized by the relational
operators or the function "memcmp"?


It is possible for different representations of a type
to correspond to the same value as determined by `=='. The
floating-point types offer a familiar example, since there
are two different representations of the value zero; there
may also be different "unnormaliz ed" representations of some
numbers. Identical representations usually imply equality
(an exception is NaN), but equality does not imply identical
representation.

As for pointers -- well, a certain widely-used architecture
supports a "segment plus offset" addressing scheme that can
address the same location with many segment/offset pairs. Or
imagine a system with (say) 48-bit addresses in 64-bit pointers;
the 16 extra bits might not participate in pointer comparisons
at all. They might even carry flags for attributes like `const'
or "obtained from malloc()" or the like, which could be useful
for debugging and validation even if they didn't contribute to
the pointer's value.

--
Eric Sosman
es*****@acm-dot-org.invalid
Jul 23 '05 #8
Ma************@ web.de writes:
No. The result of a const_cast on a pointer must refer
to the same object as the original pointer.
Note that the result of writing to an object that was
initially declared const is undefined.


How do you think about the following code example?

struct context
{
long key;
char const * name;
} ctx;

if (ctx.name = (char*) strdup(source))
{
// The string is treated as a constant after the initial assignment.
ctx.key = rand();
printf("%li: %s", ctx.key, ctx.name);

// Release memory after processing
free(deconstify 1(ctx.name));
}


strdup() is not a standard function. Assuming you're referring to the
commonly implemented function of that name, the cast is unnecessary
and potentially dangerous.

You don't show us an implementation of the deconstify1() function. (I
think it was in a previous article, but I'm too lazy to go looking for
it.)

It's generally not a good idea to use // comments in code posted to
comp.lang.c. C99 does support them, but line wrapping can cause
problems. And cross-posting to comp.lang.c and comp.lang.c++ is
almost never a good idea; they're two distinct langauges with just
enough similarities to cause arguments.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jul 23 '05 #9
[...]
As for pointers -- well, a certain widely-used architecture
supports a "segment plus offset" addressing scheme that can
address the same location with many segment/offset pairs. Or
imagine a system with (say) 48-bit addresses in 64-bit pointers;
the 16 extra bits might not participate in pointer comparisons
at all. They might even carry flags for attributes like `const'
or "obtained from malloc()" or the like, which could be useful
for debugging and validation even if they didn't contribute to
the pointer's value.


Thanks for this clear explanation.
It reminds to think about the memory layout for the compiler's internal
pointer data structure.

Are any improvements for the memory API in development to add the
capability to manipulate such flags?
Would it fit to a variant of the "realloc" programming interface to
change properties like "readable", "writeable" or "executeabl e"?
http://en.wikipedia.org/wiki/NX_bit

Regards,
Markus

Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
5085
by: Vaca Louca | last post by:
Hello, My setup: Debian sarge on dual Pentium 4. g++ 3.3.5-3. (the other system is Windows XP with MS Visual Studio .NET 2003) I have an auto_array<T> template (based on a template taken from the Corona project hosted at SourceForge) which basically wants to implement std::auto_ptr<T> semantics for an array.
134
7883
by: James A. Donald | last post by:
I am contemplating getting into Python, which is used by engineers I admire - google and Bram Cohen, but was horrified to read "no variable or argument declarations are necessary." Surely that means that if I misspell a variable name, my program will mysteriously fail to work with no error message. If you don't declare variables, you can inadvertently re-use an variable used in an enclosing context when you don't intend to, or
11
343
by: Markus.Elfring | last post by:
I am interested to know if the pointer value for the memory address can be changed by a compiler if the constness of the corresponding type is cast away. inline char* deconstify1(char const * X) { return (char*) X; } inline char* deconstify2(char const * X) { return const_cast<char*>(X); } const char source = "Test"; char* alias1 = deconstify1(source);
4
2904
by: Påhl Melin | last post by:
I have some problems using conversion operators in C++/CLI. In my project I have two ref class:es Signal and SignalMask and I have an conversion function in Signal to convert Signal:s to SignalMask:s. The reason is I have a free function called WaitSignal that accepts av SignalMask where Signals parameters are supposed to implicitly be converted to SignalMask:s. I'm using the SignalMask class because I want to be able to supply a logic...
16
2111
by: recover | last post by:
#include <string> #include <iostream> using namespace std; class TConst { private: string con; string uncon; public:
26
11740
by: =?gb2312?B?wNbA1rTzzOzKpg==?= | last post by:
i wrote: ----------------------------------------------------------------------- ---------------------------------------- unsigned char * p = reinterpret_cast<unsigned char *>("abcdg"); sizeof(reinterpret_cast<const char *>(p)); ----------------------------------------------------------------------- ---------------------------------------- the compiler tells me that "reinterpret_cast from type "const char * " to type "unsigned char *"...
21
2748
by: arnuld | last post by:
int main() { const char* arr = {"bjarne", "stroustrup", "c++"}; char* parr = &arr; } this gives an error: $ g++ test.cpp test.cpp: In function 'int main()': test.cpp:4: error: cannot convert 'const char* (*)' to 'char*' in
6
2403
by: .rhavin grobert | last post by:
hello;-) i frequently need the following construction: ReturnParam § Function() § { /...do something.../ someType var § = something; /...do something.../ return something;
6
6791
by: rahulsengupta895 | last post by:
. #define MIN(a,b) (a<b?a:b) #define MAX(a,b) (a>b?a:b) #include "Video.h" #define NO_HUE -1
0
9241
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9160
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8062
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6685
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5996
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4504
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3209
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2612
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2149
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.