473,756 Members | 6,098 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What a pointer really points to

I found the example code below, listed in the book described here:
http://cartan.cas.suffolk.edu/moin/OopDocbookWiki

The result was a bit surprising. I guess it falls into the category
of "that's what you get for lying". Can the behavior demonstrated be
explained in standardese? Yes, I know the exact result is "undefined
behavior". I can see what happened. But what was the actual violation?

// Miles are converted to kilometers.
#include <QTextStream>

QTextStream cin(stdin, QIODevice::Read Only);
QTextStream cout(stdout, QIODevice::Writ eOnly);
QTextStream cerr(stderr, QIODevice::Writ eOnly);

const double m2k = 1.609; // conversion constant

inline double mi2km(int miles) {
return (miles * m2k);
}

int main() {
int miles;
double kilometers;
cout << "Enter distance in miles: " << flush;
cin >miles ;
kilometers = mi2km(miles);
cout << "This is approximately "
<< static_cast<int >(kilometers)
<< "km."<< endl;
cout << "Without the cast, kilometers = "
<< kilometers << endl;
double* dp = const_cast<doub le*>(&m2k);
cout << "m2k: " << m2k << endl;
cout << "&m2k: " << &m2k << " dp: " << dp << endl;
cout << "*dp: " << *dp << endl;
*dp = 1.892; /* What are we attempting to do here?*/
cout << "Can we reach this statement? " << endl;
return 0;
}

/*OUT
Enter distance in miles: 23
This is approximately 37km.
Without the cast, kilometers = 37.007
m2k: 1.609
&m2k: 0x8049048 dp: 0x8049048
*dp: 1.609
Segmentation fault
*/
--
NOUN:1. Money or property bequeathed to another by will. 2. Something handed
down from an ancestor or a predecessor or from the past: a legacy of
religious freedom. ETYMOLOGY: MidE legacie, office of a deputy, from OF,
from ML legatia, from L legare, to depute, bequeath. www.bartleby.com/61/
Dec 9 '06 #1
15 1856
Steven T. Hatton wrote:
I found the example code below, listed in the book described here:
http://cartan.cas.suffolk.edu/moin/OopDocbookWiki
Well that just goes to show you don't it ;-)

#include <quan/out/length.hpp>

int main() {
std::cout << "Enter distance in miles: ";
quan::length::m i miles;
std::cin >miles.referenc e_numeric_value <quan::length:: mi>(); ;
quan::length::k m kilometers = miles;
std::cout << "\nThat is approximately " << kilometers << "\n\n";

std::cout << "Can we reach this statement?\n\n" ;
std::cout << "Sure! ... Feel the Power of The Quan :-)\n\n";
std::cout << "-------------------------------------\n";
std::cout << "Quan documentation :\n\n";
std::cout << "<http://quan.sourceforg e.net>\n\n";
std::cout << "Quan download and cvs :\n\n";
std::cout << "<http://sourceforge.net/projects/quan>\n\n";
std::cout << "-------------------------------------\n";
return 0;
}
/*
output:
Enter distance in miles: 2

That is approximately 3.21869 km

Can we reach this statement?

Sure! ... Feel the Power of The Quan :-)

-------------------------------------
Quan documentation :

<http://quan.sourceforg e.net>

Quan download and cvs :

<http://sourceforge.net/projects/quan>

-------------------------------------
*/

Dec 9 '06 #2
"Steven T. Hatton" <ch********@ger mania.supwrote in message
news:c_******** *************** *******@speakea sy.net
I found the example code below, listed in the book described here:
http://cartan.cas.suffolk.edu/moin/OopDocbookWiki

The result was a bit surprising. I guess it falls into the category
of "that's what you get for lying". Can the behavior demonstrated be
explained in standardese? Yes, I know the exact result is "undefined
behavior". I can see what happened. But what was the actual
violation?

// Miles are converted to kilometers.
#include <QTextStream>

QTextStream cin(stdin, QIODevice::Read Only);
QTextStream cout(stdout, QIODevice::Writ eOnly);
QTextStream cerr(stderr, QIODevice::Writ eOnly);

const double m2k = 1.609; // conversion constant

inline double mi2km(int miles) {
return (miles * m2k);
}

int main() {
int miles;
double kilometers;
cout << "Enter distance in miles: " << flush;
cin >miles ;
kilometers = mi2km(miles);
cout << "This is approximately "
<< static_cast<int >(kilometers)
<< "km."<< endl;
cout << "Without the cast, kilometers = "
<< kilometers << endl;
double* dp = const_cast<doub le*>(&m2k);
cout << "m2k: " << m2k << endl;
cout << "&m2k: " << &m2k << " dp: " << dp << endl;
cout << "*dp: " << *dp << endl;
*dp = 1.892; /* What are we attempting to do here?*/
cout << "Can we reach this statement? " << endl;
return 0;
}

/*OUT
Enter distance in miles: 23
This is approximately 37km.
Without the cast, kilometers = 37.007
m2k: 1.609
&m2k: 0x8049048 dp: 0x8049048
*dp: 1.609
Segmentation fault
*/
Deleting the irrelevant, you have:

const double m2k = 1.609;

int main()
{
double* dp = const_cast<doub le*>(&m2k);
*dp = 1.892;
return 0;
}

Thus dp points to a const variable and you attempt to change that const
variable using a dereferenced dp.

The operating system has presumably stored m2k in a read-only section of
memory, so raises a segmentation fault when you attempt to write to that
memory.

--
John Carson
Dec 9 '06 #3
John Carson wrote:
"Steven T. Hatton" <ch********@ger mania.supwrote in message
news:c_******** *************** *******@speakea sy.net
>I found the example code below, listed in the book described here:
http://cartan.cas.suffolk.edu/moin/OopDocbookWiki

The result was a bit surprising. I guess it falls into the category
of "that's what you get for lying". Can the behavior demonstrated be
explained in standardese? Yes, I know the exact result is "undefined
behavior". I can see what happened. But what was the actual
violation?

// Miles are converted to kilometers.
#include <QTextStream>

QTextStream cin(stdin, QIODevice::Read Only);
QTextStream cout(stdout, QIODevice::Writ eOnly);
QTextStream cerr(stderr, QIODevice::Writ eOnly);

const double m2k = 1.609; // conversion constant

inline double mi2km(int miles) {
return (miles * m2k);
}

int main() {
int miles;
double kilometers;
cout << "Enter distance in miles: " << flush;
cin >miles ;
kilometers = mi2km(miles);
cout << "This is approximately "
<< static_cast<int >(kilometers)
<< "km."<< endl;
cout << "Without the cast, kilometers = "
<< kilometers << endl;
double* dp = const_cast<doub le*>(&m2k);
cout << "m2k: " << m2k << endl;
cout << "&m2k: " << &m2k << " dp: " << dp << endl;
cout << "*dp: " << *dp << endl;
*dp = 1.892; /* What are we attempting to do here?*/
cout << "Can we reach this statement? " << endl;
return 0;
}

/*OUT
Enter distance in miles: 23
This is approximately 37km.
Without the cast, kilometers = 37.007
m2k: 1.609
&m2k: 0x8049048 dp: 0x8049048
*dp: 1.609
Segmentation fault
*/

Deleting the irrelevant, you have:
It's often nice to have something that actually compiles and runs.
Compiling the code using the Standard Library would take a trivial amount
of effort.
const double m2k = 1.609;

int main()
{
double* dp = const_cast<doub le*>(&m2k);
*dp = 1.892;
return 0;
}

Thus dp points to a const variable
What does the Standard specify it should point to, or is that specified?
and you attempt to change that const
variable using a dereferenced dp.

The operating system has presumably stored m2k in a read-only section of
memory, so raises a segmentation fault when you attempt to write to that
memory.
As I sated, I understand what happened. I'm just not sure what rule was
violated. I guess I go back to slogging my way through the artful prose of
the formal arcana of the Standard.

--
NOUN:1. Money or property bequeathed to another by will. 2. Something handed
down from an ancestor or a predecessor or from the past: a legacy of
religious freedom. ETYMOLOGY: MidE legacie, office of a deputy, from OF,
from ML legatia, from L legare, to depute, bequeath. www.bartleby.com/61/
Dec 9 '06 #4

Steven T. Hatton wrote:
What does the Standard specify it should point to, or is that specified?
The only time you can use const_cast on some object reference is when
you *know* that the real object is not const. Any const cast on a
physically const object results in undefined behaviour. The better
option on stuff you *own* is to use mutable: That is my understanding
anyway:

struct my{
private:
int n;
public:
my():n(1),y(2){ }
// mod is declared as a const function
// but maybe want to keep internal count
void mod1()const
{
// dodgy If someone declares a const my
my& mm = const_cast<my&> (*this);
++mm.n;
}
private:
mutable int y;
public:
void mod2()const
{ // always ok
++y;
}
};

int main()
{
my x;
x.mod1();
x.mod2();
}

regards
Andy Little

Dec 9 '06 #5
Steven T. Hatton wrote:
What does the Standard specify it should point to, or is that specified?
The only time you can use const_cast on some object reference is when
you *know* that the real object is not const. Any const cast on a
physically const object results in undefined behaviour. The better
option on stuff you *own* is to use mutable: That is my understanding
anyway:

struct my{
private:
int n;
public:
my():n(1),y(2){ }
// mod is declared as a const function
// but maybe want to keep internal count
void mod1()const
{
// dodgy If someone declares a const my
my& mm = const_cast<my&> (*this);
++mm.n;
}
private:
mutable int y;
public:
void mod2()const
{ // always ok
++y;
}
};

int main()
{
my x;
x.mod1();
x.mod2();
}

regards
Andy Little

Dec 9 '06 #6
Steven T. Hatton wrote:
John Carson wrote:
>"Steven T. Hatton" <ch********@ger mania.supwrote in message
news:c_******* *************** ********@speake asy.net
>>I found the example code below, listed in the book described here:
http://cartan.cas.suffolk.edu/moin/OopDocbookWiki

The result was a bit surprising. I guess it falls into the category
of "that's what you get for lying". Can the behavior demonstrated be
explained in standardese? Yes, I know the exact result is "undefined
behavior". I can see what happened. But what was the actual
violation?

// Miles are converted to kilometers.
#include <QTextStream>

QTextStream cin(stdin, QIODevice::Read Only);
QTextStream cout(stdout, QIODevice::Writ eOnly);
QTextStream cerr(stderr, QIODevice::Writ eOnly);

const double m2k = 1.609; // conversion constant

inline double mi2km(int miles) {
return (miles * m2k);
}

int main() {
int miles;
double kilometers;
cout << "Enter distance in miles: " << flush;
cin >miles ;
kilometers = mi2km(miles);
cout << "This is approximately "
<< static_cast<int >(kilometers)
<< "km."<< endl;
cout << "Without the cast, kilometers = "
<< kilometers << endl;
double* dp = const_cast<doub le*>(&m2k);
cout << "m2k: " << m2k << endl;
cout << "&m2k: " << &m2k << " dp: " << dp << endl;
cout << "*dp: " << *dp << endl;
*dp = 1.892; /* What are we attempting to do here?*/
cout << "Can we reach this statement? " << endl;
return 0;
}

/*OUT
Enter distance in miles: 23
This is approximately 37km.
Without the cast, kilometers = 37.007
m2k: 1.609
&m2k: 0x8049048 dp: 0x8049048
*dp: 1.609
Segmentatio n fault
*/

Deleting the irrelevant, you have:

It's often nice to have something that actually compiles and runs.
Compiling the code using the Standard Library would take a trivial amount
of effort.
>const double m2k = 1.609;

int main()
{
double* dp = const_cast<doub le*>(&m2k);
*dp = 1.892;
return 0;
}

Thus dp points to a const variable

What does the Standard specify it should point to, or is that specified?
It is specified in [5.2.11/3].

>and you attempt to change that const
variable using a dereferenced dp.

The operating system has presumably stored m2k in a read-only section of
memory, so raises a segmentation fault when you attempt to write to that
memory.

As I sated, I understand what happened. I'm just not sure what rule was
violated.
The code has undefined behavior according to [7.1.5.1/4].

I guess I go back to slogging my way through the artful prose
of the formal arcana of the Standard.

Best

Kai-Uwe Bux
Dec 9 '06 #7
On 2006-12-09 14:14, Steven T. Hatton wrote:
John Carson wrote:
>"Steven T. Hatton" <ch********@ger mania.supwrote in message
news:c_******* *************** ********@speake asy.net
>>I found the example code below, listed in the book described here:
http://cartan.cas.suffolk.edu/moin/OopDocbookWiki

The result was a bit surprising. I guess it falls into the category
of "that's what you get for lying". Can the behavior demonstrated be
explained in standardese? Yes, I know the exact result is "undefined
behavior". I can see what happened. But what was the actual
violation?

// Miles are converted to kilometers.
#include <QTextStream>

QTextStream cin(stdin, QIODevice::Read Only);
QTextStream cout(stdout, QIODevice::Writ eOnly);
QTextStream cerr(stderr, QIODevice::Writ eOnly);

const double m2k = 1.609; // conversion constant

inline double mi2km(int miles) {
return (miles * m2k);
}

int main() {
int miles;
double kilometers;
cout << "Enter distance in miles: " << flush;
cin >miles ;
kilometers = mi2km(miles);
cout << "This is approximately "
<< static_cast<int >(kilometers)
<< "km."<< endl;
cout << "Without the cast, kilometers = "
<< kilometers << endl;
double* dp = const_cast<doub le*>(&m2k);
cout << "m2k: " << m2k << endl;
cout << "&m2k: " << &m2k << " dp: " << dp << endl;
cout << "*dp: " << *dp << endl;
*dp = 1.892; /* What are we attempting to do here?*/
cout << "Can we reach this statement? " << endl;
return 0;
}

/*OUT
Enter distance in miles: 23
This is approximately 37km.
Without the cast, kilometers = 37.007
m2k: 1.609
&m2k: 0x8049048 dp: 0x8049048
*dp: 1.609
Segmentatio n fault
*/

Deleting the irrelevant, you have:

It's often nice to have something that actually compiles and runs.
Compiling the code using the Standard Library would take a trivial amount
of effort.
>const double m2k = 1.609;

int main()
{
double* dp = const_cast<doub le*>(&m2k);
*dp = 1.892;
return 0;
}

Thus dp points to a const variable

What does the Standard specify it should point to, or is that specified?
It should point to the const double m2k.
>and you attempt to change that const
variable using a dereferenced dp.

The operating system has presumably stored m2k in a read-only section of
memory, so raises a segmentation fault when you attempt to write to that
memory.

As I sated, I understand what happened. I'm just not sure what rule was
violated. I guess I go back to slogging my way through the artful prose of
the formal arcana of the Standard.
The violation is trying to change the value of a const. On your system
this happens to result in a segmentation fault, but there are systems
and situations where it won't.

--
Erik Wikström
Dec 9 '06 #8
kwikius wrote:
Steven T. Hatton wrote:
>What does the Standard specify it should point to, or is that specified?

The only time you can use const_cast on some object reference is when
you *know* that the real object is not const. Any const cast on a
physically const object results in undefined behaviour. The better
option on stuff you *own* is to use mutable:
My inclination is to try and figure out what I'm doing wrong, and fix it.
I've come across a couple places recently where experts "Josuttis,
Vandevoorde, Blanchette, Summerfield, etc." have used const_cast<and
defended their choice. Nonetheless...
That is my understanding
anyway:

struct my{
private:
int n;
public:
my():n(1),y(2){ }
// mod is declared as a const function
// but maybe want to keep internal count
void mod1()const
{
// dodgy If someone declares a const my
my& mm = const_cast<my&> (*this);
++mm.n;
}
private:
mutable int y;
public:
void mod2()const
{ // always ok
++y;
}
};

int main()
{
my x;
x.mod1();
x.mod2();
}
I know what Stroustrup had to say about mutable. He thinks it is almost
always a bad idea because it defeats the purpose of const. But the same
goes for const_cast only more so.

Here's my hack on the subsequent example from
http://cartan.cas.suffolk.edu/moin/OopDocbookWiki

#include <iostream>
using namespace std;

void el() {
const int L = 99;
int * pL = const_cast<int* >(&L);
*pL = 101;
cout << L << '\t' << &L << endl;
cout << *pL << '\t' << pL << endl;
}

void em() {
const int M = 29;
int * pM = const_cast<int* >(&M);
*pM = 66;
cout << M << '\t' << &M << endl;
cout << *pM << '\t' << pM << endl;
}

const int N = 22;
void en() {

int * pN = const_cast<int* >(&N);
*pN = 33;
cout << N << '\t' << &N << endl;
cout << *pN << '\t' << pN << endl;
}

int main() {
el();
em();
en();
}
/*
Sat Dec 09 09:06:25:c++ -o cc1 constcast1.cpp
hattons@ljosalf r:~/code/c++/ezust/src/casts/
Sat Dec 09 09:06:46:./cc1
99 0xbfc2ccb0
101 0xbfc2ccb0
29 0xbfc2ccb0
66 0xbfc2ccb0
Segmentation fault

*/

The authors are saying that[*] "const int is in stack storage class". I
believe that is old-timer talk meaning 'automatic variable' but I'm not
sure. I have a couple of observations about the code above, and the result
of executing it. The addresses of all the variables which were printed
prior to the segfault are the same. The segfault happened when the
variable was placed at global scope. If nothing else, it shows that
undefined behavior is undefined.
[*]If I understand correctly.
--
NOUN:1. Money or property bequeathed to another by will. 2. Something handed
down from an ancestor or a predecessor or from the past: a legacy of
religious freedom. ETYMOLOGY: MidE legacie, office of a deputy, from OF,
from ML legatia, from L legare, to depute, bequeath. www.bartleby.com/61/
Dec 9 '06 #9

Steven T. Hatton wrote:
Here's my hack on the subsequent example from
http://cartan.cas.suffolk.edu/moin/OopDocbookWiki
>
#include <iostream>
using namespace std;

void el() {
const int L = 99;
int * pL = const_cast<int* >(&L); // use pL and its undefined
*pL = 101; //undefined behaviour
cout << L << '\t' << &L << endl;
cout << *pL << '\t' << pL << endl;
}

void em() {
const int M = 29;
int * pM = const_cast<int* >(&M); // same applies
*pM = 66; //undefined behaviour
cout << M << '\t' << &M << endl;
cout << *pM << '\t' << pM << endl;
}

const int N = 22;
void en() {

int * pN = const_cast<int* >(&N); // and here
*pN = 33; //undefined behaviour
cout << N << '\t' << &N << endl;
cout << *pN << '\t' << pN << endl;
}
All undefined . The only time you can use const_cast is if you know
something is not but looks like it is:
// object pointed by p is 'logically const'
int f( const int & p)
{
int & pp = const_cast<int& >(p);
++pp; // behaviour here dependent on whether
// object referenced by pp is "physically const" or not
// if object is really const... undefined behaviour

return pp;
}

int main()
{
int x=0;
f(x); // OK... x is not really const

const int y =0;
f(y); // Bad.. y Is really const ...undefined behaviour
}

regards
Andy Little

Dec 9 '06 #10

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

Similar topics

12
3303
by: Steven T. Hatton | last post by:
This is something I've been looking at because it is central to a currently broken part of the KDevelop new application wizard. I'm not complaining about it being broken, It's a CVS images. Such things happen. The whole subsystem is going through radical changes. I don't really want to say what I think of the code just yet. That would influence the opinions of others, and I really want to know how other people view these things,...
6
2577
by: Alfonso Morra | last post by:
I have written the following code, to test the concept of storing objects in a vector. I encounter two run time errors: 1). myClass gets destructed when pushed onto the vector 2). Prog throws a "SEGV" when run (presumably - attempt to delete deleted memory. Please take a look and see if you can notice any mistakes I'm making. Basically, I want to store classes of my objects in a vector. I also have three further questions:
15
2780
by: damian birchler | last post by:
Hi I'm wondering of what type a structure is. Of course, it is a _structure_, but an array isn't an _array_ either. So of what type is a structure? I'd say a pointer, am I right?
9
56195
by: weaselboy1976 | last post by:
Hello How can I print a pointer's value directly (without assigning the value to another variable)? For example: #include <stdio.h> int main() { int *zp;
204
13064
by: Alexei A. Frounze | last post by:
Hi all, I have a question regarding the gcc behavior (gcc version 3.3.4). On the following test program it emits a warning: #include <stdio.h> int aInt2 = {0,1,2,4,9,16}; int aInt3 = {0,1,2,4,9};
6
2295
by: Itay_k | last post by:
Hello, I want a member in my class that will save pointer to pointer to System::Drawing::Image class. When I write on my class code: System::Drawing::Image **bmp; I get this error message: error C3160: 'bmp' : cannot declare interior __gc pointer or reference as a
3
29698
by: David Mathog | last post by:
I have a program for which this line: if(! lstrtol(&atoken,length-2,(long *) &(lclparams->pad)) || (lclparams->pad< 0)){ generates the warning below, but ONLY if the gcc compiler is at -O2 or -O3. I don't see any reason why optimization should change things much in this piece of code - there's no way to optimize it out and I have verified that this particular line does what it should no matter how the program is compiled. Anyway,...
29
7882
by: marvinla | last post by:
Hello! I'm a beginner in C, and I'm having trouble with a pointer-to-pointer reallocation. This piece of code works well, but Valkyrie warns some parts (pointed below), and is breaking my real code. #include <stdio.h> #include <stdlib.h>
41
3660
by: Summercool | last post by:
Can we confirm the following? also someone said, Java also has "reference" like in C++, which is an "implicit pointer": Pointer and Reference --------------------- I am starting to see what pointer and reference are and how they relate to each other.
0
9454
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
9271
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
10028
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
9868
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
9836
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
9707
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...
0
8709
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...
0
5301
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3352
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.