473,695 Members | 2,098 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why doesn't this work? (pointers)

I wrote the following program to demonstrate an oddity I found in C++.

#include <iostream>
using namespace std;
int main()
{int *p, *q;
p = q;
q = new int;
*q = 12;
cout << *p;
system("pause") ;
return 0;
}
Your compiler will either give a gibberish answer or crash when you try
to run this program.
Here's what I don't understand: p and q are pointing to the same memory
address. That being said, why can't you access the dynamic variable using
p as well as q?
What would happen if you created a new variable using p too? Aren't they
both pointing to the same memory? Would they overwrite each other?

Thanks.

-==Kensu==-
I actually came across this while working with a homemade linked list.
You can imagine how frustrating THAT was...
Jul 22 '05 #1
22 1484
On Sun, 10 Oct 2004 22:22:00 GMT, Chris Schumacher <ke*****@hotmai l.com> wrote:
q = new int;


Here new allocates space for an int, and returns the location of the new
object, so this assignment overwrites any previous value of q. And besides, you
never initialised the old q, so it was full of garbage even before this line.

You must find a place to store an int (using new or a variable), then set both
p and q to point to it. Use

p = q;

after the "new" line to do this.

Turn on warnings in your compiler and it will likely detect the use of
uninitialised variables.

--
Ben Caradoc-Davies <be*@wintersun. org>
http://wintersun.org/
Jul 22 '05 #2
Chris Schumacher wrote:
I wrote the following program to demonstrate an oddity I found in C++.

#include <iostream>
using namespace std;
int main()
{int *p, *q;
Here p and q are initialised and thus point to "random" areas in memory.

p = q;
Here the "random" memory address stored in q is assigned to p.
q = new int;

Here an int is created in the free store and its address is assigned to
q pointer variable.
*q = 12;

Here the address stored in q is dereferenced, and the int pointed is
assigned the value 12.
cout << *p;

Here you dereference the "random" memory value assigned to p in the
beginning, and you read some "random" memory portion of the program,
invoking undefined behaviour.

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #3
Chris Schumacher wrote:
I wrote the following program to demonstrate an oddity I found in C++.

#include <iostream>
using namespace std;
int main()
{int *p, *q;
1. Both the pointer variables are not initialized.
p = q;
2. You are assigning one of them to the other.
q = new int;
3. You are allotting a chunk of memory and q stores the pointer to that
location.

*q = 12;
4. You are storing a particular value in the memory pointed to , by q.

cout << *p;


5. (3) and (4) still do not affect p anyway. p is still
uninitialized and dereferencing it results in UB.

As Ben had already pointed out, you can do
the assignemnt 'p = q' after allocating memory for q.
Otherwise it does not help anyway.

--
Karthik. http://akktech.blogspot.com .
' Remove _nospamplz from my email to mail me. '
Jul 22 '05 #4
Correction:
Ioannis Vranos wrote:
Here p and q are

uninitialised

and thus point to "random" areas in memory.

Jul 22 '05 #5
Ben Caradoc-Davies <be*@wintersun. org> wrote in
news:sl******** ********@localh ost.localdomain :
On Sun, 10 Oct 2004 22:22:00 GMT, Chris Schumacher
<ke*****@hotmai l.com> wrote:
q = new int;


Here new allocates space for an int, and returns the location of the
new object, so this assignment overwrites any previous value of q. And
besides, you never initialised the old q, so it was full of garbage
even before this line.


Ah, I see now. Thanks.
Both of the textbooks I used seemed to gloss over the fact that pointers
are not initalized during declaration. They made it seem that the new int
or whatever is placed in the memory location that the variable is pointing
at when declared.

Thanks again, to everyone who replied.
-==Kensu==-
Jul 22 '05 #6

"Chris Schumacher" <ke*****@hotmai l.com> wrote in message
news:Xn******** *************** ******@207.115. 63.158...
I wrote the following program to demonstrate an oddity I found in C++.
The 'oddity' is in your code, not the language
#include <iostream>
using namespace std;
int main()
{int *p, *q;
There now exist two pointers, named 'p' and 'q'.
Neither has a defined, valid value. Any attempt
to evaluate the value of either will produce
'undefined behavior' (which means anything can
happen, from 'appearing to work' to a crash,
or anything else.
p = q;
Kaboom. Evalution of unintialized object.
q = new int;
Allocates storage sufficient to store a single type
'int' object, and stores the address of this storage
in the pointer 'q'.
*q = 12;
Assigns the value 12 to the allocated type 'int' object.
cout << *p;
Kaboom again. Evalution of an ininitialized object.


system("pause") ;
return 0;
}
Your compiler will either give a gibberish answer or crash when you try
to run this program.
According to the definition of the language, it can do absolutely
anything (or nothing) at all.
Here's what I don't understand: p and q are pointing to the same memory
address.
They are not. 'p' doesn't point anywhere. 'q' points to an
allocated type 'int' object.
That being said,
Saying it doesn't make it so. :-)
why can't you access the dynamic variable using
p as well as q?
Because 'p' does not point anywhere. (It might 'by accident',
but officially its value is undefined.)

What would happen if you created a new variable using p too?
You can allocate another 'int' and assign its addres to 'p'.
If you did, then 'p' would have the same behavior as 'q' (except
that it would point to a different object.).
Aren't they
both pointing to the same memory?
No. Nothing in your code has assigned the address of the
allocated 'int' to 'p'.
Would they overwrite each other?
Only if you write code to do so.
I actually came across this while working with a homemade linked list.
You can imagine how frustrating THAT was...


Yes, I imagine expecting behavior based upon a false assumption
would be frustrating. :-)

-Mike

Jul 22 '05 #7
"Chris Schumacher" <ke*****@hotmai l.com> wrote in message
news:Xn******** *************** ******@207.115. 63.158...
Ben Caradoc-Davies <be*@wintersun. org> wrote in
news:sl******** ********@localh ost.localdomain :
On Sun, 10 Oct 2004 22:22:00 GMT, Chris Schumacher
<ke*****@hotmai l.com> wrote:
q = new int;
Here new allocates space for an int, and returns the location of the
new object, so this assignment overwrites any previous value of q. And
besides, you never initialised the old q, so it was full of garbage
even before this line.


Ah, I see now. Thanks.
Both of the textbooks I used seemed to gloss over the fact that pointers
are not initalized during declaration.


That is not a 'fact'. The fact is that objects of automatic
storage duration are not automatically initialized. Their
type doesn't matter. Objects with static storage duration
are automatically initialized (to 0).
They made it seem that the new int
or whatever is placed in the memory location that the variable is pointing
at when declared.


A definition of a pointer *never* will cause it to point
anywhere unless you supply an initializer. This is the
case for a pointer of any storage duration.

Which textbooks are you referring to?

-Mike
Jul 22 '05 #8

"Ioannis Vranos" <iv*@guesswh.at .grad.com> wrote in message
news:1097448661 .181043@athnrd0 2...
Chris Schumacher wrote:
I wrote the following program to demonstrate an oddity I found in C++.

#include <iostream>
using namespace std;
int main()
{int *p, *q;
Here p and q are initialised


Uninitialised. (But I'm sure that's what you meant).

and thus point to "random" areas in memory.
They might, they might not. Their values are undefined.
p = q;


Here the "random" memory address stored in q is assigned to p.


1) (The randome 'value' of 'q' might or might not correspond to
valid memory addresses.

2) Because of 1), no assignment at all is required to take place.
q = new int;


Here an int is created in the free store and its address is assigned to
q pointer variable.
*q = 12;


Here the address stored in q is dereferenced, and the int pointed is
assigned the value 12.
cout << *p;


Here you dereference the "random" memory value


First, this causes the value of 'p' to be evaluted, producing
undefined behavior. A dereference might or might not happen.
And if such a dereference did somehow succeed, another evaluation
of an ininitialized object would happen, resulting again in
undefined behavior.
assigned to p in the
beginning, and you read some "random" memory portion of the program,
invoking undefined behaviour.


The entire program's behavior becomes undefined as soon
as the expression p=q is evaluated.

-Mike
Jul 22 '05 #9
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:60******** *********@newsr ead1.news.pas.e arthlink.net...

"Ioannis Vranos" <iv*@guesswh.at .grad.com> wrote in message
news:1097448661 .181043@athnrd0 2...
Chris Schumacher wrote:
I wrote the following program to demonstrate an oddity I found in C++.

#include <iostream>
using namespace std;
int main()
{int *p, *q; p = q;


The entire program's behavior becomes undefined as soon
as the expression p=q is evaluated.


Make that "as soon as the expression 'q' is evaluated the first time"

-Mike
Jul 22 '05 #10

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

Similar topics

9
1454
by: Mika Vainio | last post by:
hi everybody, i'm working on the following problem: i need to build a 26-nary tree to save a data dictionary. every letter of the words is represented by a cell (cell has a pointer-vector cell* children). the last letter is a node (node:cell, additional property "pagenr"). now: i understood the principals of polymorph objects and it worked fine with the ususal examples. but in my case it does not! there is no compilation or linking error...
5
2028
by: nick | last post by:
I have the following code: var ocevent = function(v) { alert('javascript event: u clicked '+v); return false; };
149
25141
by: Christopher Benson-Manica | last post by:
(Followups set to comp.std.c. Apologies if the crosspost is unwelcome.) strchr() is to strrchr() as strstr() is to strrstr(), but strrstr() isn't part of the standard. Why not? -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
8
1208
by: Rob | last post by:
I have a vector of a class type and when I create an object inside a function and return that and add it to the vector, it doesn't properly keep the data inside it. So I have a few questions: 1. Is this because it loses scope since it wasn't created with "new"? 2. If I do create it with new, but the vector holds objects not pointers, will the vector's "delete" operator function still handle deleting all those pointers? CODE 1:
0
8578
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
8998
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
8857
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
8831
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
5841
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
4346
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...
0
4586
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3013
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
3
1979
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.