473,769 Members | 2,359 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A few things that puzzle me...

Okay firstly I'll start with pointers. I have always thought of a pointer as
storage which holds a memory address, plain and simple. Let's say that on a
particular platform, an "int" is 32-Bit, and a memory address is 32-Bit.
Thus, if we have the following code:

int i = 7;

int* p = &i;

Then memory is allocated to store a 32-Bit "int", and the value "7" is
stored in it. Let's say that the address of this memory is 0x89ABCDEF. Now,
we store the address of "i" in the variable "p". So "p"'s value will be
0x89ABCDEF. They'll look like so in memory:

i: 0000 0000 0000 0000 0000 0000 0000 0111

p: 1000 1001 1010 1011 1100 1101 1110 1111
One of the first delicate matters about pointers is that a null pointer
isn't necessarily represented as all bits zero, as follows:

0000 0000 0000 0000 0000 0000 0000 0000
But, depending on the platform, it could have any bit pattern, such as:

1000 0000 0000 0000 0000 0000 0000 0000

or:

1111 1111 1111 1111 1111 1111 1111 1111
When you write the following in your code:

p = 0;

Then you're storing the null pointer value in a pointer variable, which may
or may not be the same bit pattern as integral zero.

Moving on...

Because of my understanding of a pointer as just storing a memory address, I
fail to understand why the following code wouldn't be legal:

int a;

int* p1 = &a;

char* p2 = reinterpret_cas t<char*>( p1 );

double* p3 = reinterpret_cas t<double*>( p2 );

std::string* p4 = reinterpret_cas t<std::string*> ( p3 );

int* p5 = reinterpret_cas t<int*>(p4);

*p5 = 3;
I've often heard that the above code might not do what I expect it to do.
This leads me to believe that not all pointer types are the same. So my
first question is:

A) How are different pointer types different? My understanding is that they
simply store a memory address, so I would imagine they would all be the
same.
Another question which comes to mind is:

B) Do all pointer types have the same null value? Or can different types
have different null values?
Is there any sort of in-depth guide which deals with all the fanciful
possibilites of pointers?

And finally, is the following code legal:

int (&array)[5] = *reinterpret_ca st< int (*)[5] > ( new int[5] );

delete &array[0];
If we look at it from the viewpoint of a pointer as simply storing a memory
address, then I forsee no problems with the above code.

-Tomás
Mar 18 '06 #1
7 1623
* Tomás:

A) How are different pointer types different? My understanding is that they
simply store a memory address, so I would imagine they would all be the
same.
Depends much on the machine. C++ logical requirements only tell you
that an ordinary data pointer might be of smaller size than a pointer to
member function. Then again, a conforming compiler can have
sizeof(bool) equal 10 000, just to take a number, and likewise for
pointers; although unnatural, the standard places no limits on size.
Another question which comes to mind is:

B) Do all pointer types have the same null value? Or can different types
have different null values?
Not necessarily, and yes.

Is there any sort of in-depth guide which deals with all the fanciful
possibilites of pointers?
Not as far as I know. It's best to avoid the fanciful anyway.

And finally, is the following code legal:

int (&array)[5] = *reinterpret_ca st< int (*)[5] > ( new int[5] );

delete &array[0];
new[] used to allocate, delete to deallocate, oops.

Apart from that the reinterpret_cas t may or may not do what you expect
it to.

Instead you should do

std::vector<int > array( 5 );

Get it?

If we look at it from the viewpoint of a pointer as simply storing a memory
address, then I forsee no problems with the above code.


Uh oh...
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Mar 18 '06 #2
Tomás <NU**@NULL.NULL > wrote:
int a;

int* p1 = &a;

char* p2 = reinterpret_cas t<char*>( p1 );

double* p3 = reinterpret_cas t<double*>( p2 );

std::string* p4 = reinterpret_cas t<std::string*> ( p3 );

int* p5 = reinterpret_cas t<int*>(p4);

*p5 = 3;
I've often heard that the above code might not do what I expect it to
do. This leads me to believe that not all pointer types are the same.
The above is legal. One could argue about it being unspecified (and
thus being unportable) or not. See 5.2.10/7.
And finally, is the following code legal:

int (&array)[5] = *reinterpret_ca st< int (*)[5] > ( new int[5] );

delete &array[0];


Despite the mismatching delete call, this is *not* undefined, but
unspecified. In other words, you are not going to be portable with this.

regards
--
jb

(reply address in rot13, unscramble first)
Mar 18 '06 #3

Tomás wrote:
Because of my understanding of a pointer as just storing a memory address, I
fail to understand why the following code wouldn't be legal:

int a;

int* p1 = &a;

char* p2 = reinterpret_cas t<char*>( p1 );

double* p3 = reinterpret_cas t<double*>( p2 );

std::string* p4 = reinterpret_cas t<std::string*> ( p3 );

int* p5 = reinterpret_cas t<int*>(p4);

*p5 = 3;
The code is legal but its behavior is undefined.
I've often heard that the above code might not do what I expect it to do.
This leads me to believe that not all pointer types are the same. So my
first question is:

A) How are different pointer types different? My understanding is that they
simply store a memory address, so I would imagine they would all be the
same.
No, all pointer types are not the same. Types usually have alignment
requirements - which means that an object of that type can reside only
at certain addresses. And the fact that different types may have
different alignment requirements means that casting from one type to
another and back again is not guaranteed to point to the same memory
location as the original. So the behavior of the above code is
undefined.
Another question which comes to mind is:

B) Do all pointer types have the same null value? Or can different types
have different null values?
Not in a way that a program would ever be able to tell.
And finally, is the following code legal:

int (&array)[5] = *reinterpret_ca st< int (*)[5] > ( new int[5] );

delete &array[0];


Since the program allocates an array of five ints and deletes a pointer
to one int, the program is not correct.

Greg

Mar 18 '06 #4
And finally, is the following code legal:

int (&array)[5] = *reinterpret_ca st< int (*)[5] > ( new int[5] );

delete &array[0];

Should've written:

delete [] &array[0];
Mar 18 '06 #5
Tomás wrote:
A) How are different pointer types different? My understanding is that they
simply store a memory address, so I would imagine they would all be the
same.


They are all memory addresses, but they are not all the same. In C++
each one of them has a type. The type information (maintained by the
compiler) determines the size and type of what the pointer reads/writes.
The type information also determines the size of the address offset to
add when the pointer is "incremente d."

--
Scott McPhillips [VC++ MVP]

Mar 18 '06 #6
Tomás wrote:
[snipped unnessesary speech about OP's platform's pointer representation]

Because of my understanding of a pointer as just storing a memory address, I
fail to understand why the following code wouldn't be legal:

int a;

int* p1 = &a;

char* p2 = reinterpret_cas t<char*>( p1 );

double* p3 = reinterpret_cas t<double*>( p2 );

std::string* p4 = reinterpret_cas t<std::string*> ( p3 );

int* p5 = reinterpret_cas t<int*>(p4);

*p5 = 3;

What you have failed to understand is the way the Standard deals with
pointers. There are very few guarantees about reinterpret_cas t'ing a
pointer, even fewer are about pointer's bit representation.

[5.2.10/3]
The mapping performed by reinterpret_cas t is implementation-defined.

You can make no assumptions about the actual value of 'p2'. In
particular (however illogical it may seem), you cannot portably use 'p2'
to access the first byte of 'a'. The only thing that you can reliably do
with 'p2' is convert it back to 'int *' (assuming that char's alignment
is less or equal to int's alignment):

[5.2.10/7]
A pointer to an object can be explicitly converted to a pointer to an
object of different type. Except that converting an rvalue of type
"pointer to T1" to the type "pointer to T2" (where T1 and T2 are object
types and where the alignment requirements of T2 are no stricter than
those of T1) and back to its original type yields the original pointer
value, the result of such a pointer conversion is unspecified.

Without implementaion-specific information, it is impossible to say
whether "p1 == p5". With your implementation, it may hold. With mine, it
might not.
I've often heard that the above code might not do what I expect it to do.
This leads me to believe that not all pointer types are the same. So my
first question is:

A) How are different pointer types different? My understanding is that they
simply store a memory address, so I would imagine they would all be the
same.
_Different_ pointer types are different, because they point to objects
of _different_ type. The fact that you're asking questions about bit
representation of pointers suggests that you are introducing
non-portable features into your program.
B) Do all pointer types have the same null value? Or can different types
have different null values?
Are you asking about bit representations again (see above)? Just don't.
(And no, there is no such guarantee. The Standard doesn't talk about
bits in this respect very often.)
Is there any sort of in-depth guide which deals with all the fanciful
possibilites of pointers?
The Standard should be the source to consider. It may be harder to read
though. Unfortunately, I don't know of any books that could be useful to
you. Mr. Bazarov is usualy the one throwing book suggestions about ;-)
And finally, is the following code legal:

int (&array)[5] = *reinterpret_ca st< int (*)[5] > ( new int[5] );
delete &array[0];


I rewrote the code to make it more understandable:

int * p = new int[5];
int (*array)[5] = reinterpret_cas t<int(*)[5]> (p);

See above; 'array' holds an implementation-defined value. You can use it
neither to access the array you allocated nor to delete it. You *can* say:

int * q = reinterpret_cas t<int *> (array);
delete[] q;

I hope I made it clearer for you.
Martin
Mar 19 '06 #7
Tomás wrote:
Okay firstly I'll start with pointers. I have always thought of a pointer
as storage which holds a memory address, plain and simple. Let's
say that on a particular platform, an "int" is 32-Bit, and a memory
address is 32-Bit.
Thus, if we have the following code:

int i = 7;

int* p = &i;

Then memory is allocated to store a 32-Bit "int", and the value "7" is
stored in it. Let's say that the address of this memory is 0x89ABCDEF
. Now, we store the address of "i" in the variable "p". So "p"'s value will
be 0x89ABCDEF. They'll look like so in memory:

i: 0000 0000 0000 0000 0000 0000 0000 0111

p: 1000 1001 1010 1011 1100 1101 1110 1111
Well, it might. The system could store the four bytes
0xEF, 0xCD, 0xAB, 0x89. Or it could store every byte twice
and use 64 bits of storage (although that would be inefficient).
In short, the address can be stored in any way that is
convenient for the compiler, as long as the address can be
successfully retrieved from the storage when it is needed.
Because of my understanding of a pointer as just storing a memory address, I
fail to understand why the following code wouldn't be legal:

int a;

int* p1 = &a;
char* p2 = reinterpret_cas t<char*>( p1 );
double* p3 = reinterpret_cas t<double*>( p2 );
You could have alignment trouble here. For example, some
systems could require that a 'double' only exist where its
address is a multiple of 8, but ints can exist anywhere with
an address of any multiple of 4. If this is the case, and
the address in p2 is not a multiple of 8, then you have caused
undefined behaviour and you're likely to get an error thrown
by the operating system here.

Going back to the topic of representation of pointer values;
a system with 8-byte alignment for doubles might choose
to right-shift the address of the double by 3 bits (which have
to be 0 anyway) before storing it. This has the advantage of
not allowing you to address 32Gb of doubles instead of
4Gb, with a 32-bit pointer.
std::string* p4 = reinterpret_cas t<std::string*> ( p3 );
Same alignment problem again here. Also, of course, if you
actually try and dereference this pointer you're very unlikely
to have a valid string object there.
int* p5 = reinterpret_cas t<int*>(p4);
*p5 = 3;
This is oK
I've often heard that the above code might not do what I expect it to do.
This leads me to believe that not all pointer types are the same.
They may all have different sizes and representations (except for
void*, char* and unsigned char* which must all be the same).
A) How are different pointer types different? My understanding is that they
simply store a memory address, so I would imagine they would all be the
same.
See above. There's more to "A memory address" than "A 32 bit number".
For example, 16-bit segmented architectures, or systems where the
'memory' is a reel of magnetic tape (Unlikely but possible).
Another question which comes to mind is:

B) Do all pointer types have the same null value? Or can different types
have different null values?
There is only one null value. But the representations of null can all
be different.

And finally, is the following code legal:

int (&array)[5] = *reinterpret_ca st< int (*)[5] > ( new int[5] );


An (int *) might not be correctly aligned for an int (*)[5] .
(In practice this probably would never happen).

Mar 20 '06 #8

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

Similar topics

1
6109
by: Developwebsites | last post by:
Hi all, I've made a sliding puzzle game in shockwave which works just fine, except I dont know how to have it solve itself. the URL is: http://members.aol.com/rglukov/games/selfsolve.htm There are lots of these on the net, made in java, flash, C++, javascript, etc. and as shareware, but none seem to be solving the puzzle by
42
2991
by: Frank Buss | last post by:
I've setup a challenge, mainly for C++, Java and Lisp, but every other language is welcome: http://www.frank-buss.de/challenge/index.html There is nothing to win, but I hope there will be some interesting solutions at the end, so the win are the results :-) -- Frank Buß, fb@frank-buss.de
1
13105
by: xavier vazquez | last post by:
I have a problem with a program that does not working properly...when the program run is suppose to generate a cross word puzzle , when the outcome show the letter of the words overlap one intop of the other....how i can fix this the program look like this import java.util.ArrayList; import java.util.Random;
0
2025
by: xavier vazquez | last post by:
have a problem with a program that does not working properly...when the program run is suppose to generate a cross word puzzle , when the outcome show the letter of the words overlap one intop of the other....how i can fix this this run the random words for the program import javax.swing.JOptionPane; import java.util.ArrayList; import java.util.Random; public class CrossWordPuzzleTester {
5
4470
by: ashish0799 | last post by:
HI I M ASHISH I WANT ALGORYTHMUS OF THIS PROBLEM Jigsaw puzzles. You would have solved many in your childhood and many people still like it in their old ages also. Now what you have got to do is to solve jigsaw puzzles using the computer. The jigsaw puzzle here is a square of dimension d (a puzzle with d^2 pieces) and the jigsaw pieces (all same dimensions) are of dimensions H x W (Which means the pieces have ‘H’ rows of ‘W’...
3
3207
by: oncue01 | last post by:
Word Puzzle Task You are going to search M words in an N × N puzzle. The words may have been placed in one of the four directions as from (i) left to right (E), (ii) right to left (W), (iii) up to bottom (S), or (iv) bottom to up (N). The program will print the starting place and the direction of each word. Limitations The number of words to be searched can be at most 100, the size of the puzzle N can be minimum 5 maximum 20....
6
2576
by: Phoe6 | last post by:
Hi All, I would like to request a code and design review of one of my program. n-puzzle.py http://sarovar.org/snippet/detail.php?type=snippet&id=83 Its a N-puzzle problem solver ( Wikipedia page and http://norvig.com/ltd/test/n-puzzle.lisp ) I have used OO Python for the above program and would like comments on my approach as I am just starting with OOP.
2
2703
by: Gio | last post by:
I'm getting K&R (it's on the way), should I also get the Answer Book? And while I'm there, should I get the Puzzle Book? Or should I save the Puzzle Book for when I'm more advanced? - Gio -- AND NOW FOR A WORD (an IF blog):
4
19994
by: honey777 | last post by:
Problem: 15 Puzzle This is a common puzzle with a 4x4 playing space with 15 tiles, numbered 1 through 15. One "spot" is always left blank. Here is an example of the puzzle: The goal is to get the tiles in order, 1 through 15, from left to right, top to bottom, by just sliding tiles into the empty square. In this configuration, the goal would be to get the 14 and 15 to switch places, without affecting any of the other squares. Your...
5
4843
by: dmf1207 | last post by:
Hi All! I'm new to javascript and need a little help with a simple puzzle im trying to design. I have a 600x100 pixel picture that I have sliced into 6 100x100 rectangles making a table of of 6 columns and 1 row. I wanted to make a "swap puzzle" where the user clicks on one image then the other and they swap. At first load i want to have the puzzle in a scrambled order and then when they complete it I want to alert the user with how many clicks...
0
9586
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10210
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9861
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7406
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
5298
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
3956
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
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2814
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.