473,322 Members | 1,401 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

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(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);
char* alias2 = deconstify2(source);

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 2366
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(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);
char* alias2 = deconstify2(source);

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(char const * X) { return (char*) X; }
inline char* deconstify2(char const * X) { return const_cast<char*>(X);
}
These two mean the exact same thing.
const char source [] = "Test";
char* alias1 = deconstify1(source);
char* alias2 = deconstify2(source);

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(source);
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 interchangeability 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(deconstify1(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 "unnormalized" 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(deconstify1(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_Keith) 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 "executeable"?
http://en.wikipedia.org/wiki/NX_bit

Regards,
Markus

Jul 23 '05 #10
> 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.)
How do you think about this code example?

struct context
{
long key;
char const * name1;
string const * name2;
} ctx;

char* X = (char*) malloc(5);

if (X)
{
strcpy(X, "Test");
ctx.name1 = X;
ctx.name2 = new string("check");

/* Treat it as a constant after the initial assignment */
if (ctx.name2)
{
ctx.key = rand();
printf("%li: %s", ctx.key, ctx.name1);
cout << *ctx.name2;

{
string* alias1 = const_cast<string*>(ctx.name2);

if (memcmp(ctx.name2, alias1, sizeof(alias1)))
{
printf("1. changed representation: %p %p", ctx.name2, alias1);
}

delete alias1;
}
}

/* Release memory after processing */
{
char* alias2 = (char*) ctx.name1;

if (memcmp(ctx.name1, alias2, sizeof(alias2)))
{
printf("2. changed representation: %p %p", ctx.name1, alias2);
}

free(alias2);
}
}

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.


Well, I try to discuss some details for common sense.

Regards,
Markus

Jul 23 '05 #11
Ma************@web.de wrote:
How do you think about this code example?


*What* I think about your C++ code example is that it ought not be
posted to comp.lang.c. Please pay attention to what you are doing.
Follow-ups set.
Jul 23 '05 #12
Ma************@web.de wrote:
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.)
How do you think about this code example?


Very little.

struct context
{
long key;
char const * name1;
string const * name2;
You haven't defined 'string'.
} ctx;

char* X = (char*) malloc(5);
You should NEVER cast the return from malloc. Where did the magic
number '5' come from?

if (X)
{
strcpy(X, "Test");
ctx.name1 = X;
ctx.name2 = new string("check");
'new' is a syntax error. This is c.l.c, not c.l.c++.
/* Treat it as a constant after the initial assignment */
if (ctx.name2)
{
ctx.key = rand();
printf("%li: %s", ctx.key, ctx.name1);
cout << *ctx.name2;
You haven't defined cout. Why do you want to left shift it?
*ctx.name2 is not a suitable argument anyhow.

{
string* alias1 = const_cast<string*>(ctx.name2);


More syntax errors. Again, this is c.l.c.

.... snip remainder. F'ups set. c.l.c / c.l.c++ crossposts are
pure foolishness.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Jul 23 '05 #13

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

Similar topics

7
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...
134
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...
11
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)...
4
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...
16
by: recover | last post by:
#include <string> #include <iostream> using namespace std; class TConst { private: string con; string uncon; public:
26
by: =?gb2312?B?wNbA1rTzzOzKpg==?= | last post by:
i wrote: ----------------------------------------------------------------------- ---------------------------------------- unsigned char * p = reinterpret_cast<unsigned char *>("abcdg");...
21
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...
6
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
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
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.