473,545 Members | 2,469 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

assigning a pointer the address of local variable

Suppose I have a code like this,

#include <stdio.h>

int *p;
void foo(int);

int main(void){
foo(3);
printf("%p %d\n",p,*p);
return 0;
}

void foo(int r){
int s=r+1;
p=&s;
}

In most of the compilers I use (GCC, MSVC++, lcc..) this program runs
allright printing an address and the correct value 4. But is it correct
to assign a global pointer the address of a local variable which does
not exist after the function has ended?

Aug 23 '06 #1
25 9501
"Sourav" <so*********@gm ail.comwrites:
Suppose I have a code like this,

#include <stdio.h>

int *p;
void foo(int);

int main(void){
foo(3);
printf("%p %d\n",p,*p);
return 0;
}

void foo(int r){
int s=r+1;
p=&s;
}

In most of the compilers I use (GCC, MSVC++, lcc..) this program runs
allright printing an address and the correct value 4. But is it correct
to assign a global pointer the address of a local variable which does
not exist after the function has ended?
No, it isn't. When s reaches the end of its lifetime (at the end of
foo(), the value of p becomes indeterminate. Dereferencing p, or even
looking at its value, invokes undefined behavior. (The latter isn't
likely to cause any visible problems on most systems, but you should
still avoid it.)

--
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.
Aug 23 '06 #2

Sourav wrote:
Suppose I have a code like this,

#include <stdio.h>

int *p;
void foo(int);

int main(void){
foo(3);
printf("%p %d\n",p,*p);
return 0;
}

void foo(int r){
int s=r+1;
p=&s;
}

In most of the compilers I use (GCC, MSVC++, lcc..) this program runs
allright printing an address and the correct value 4. But is it correct
to assign a global pointer the address of a local variable which does
not exist after the function has ended?
No. consider:

#include <stdio.h>

int *p;
void foo(int);
int baz(int);

int main(void){
foo(3);
baz(5);
printf("%p %d\n",(void*)p, *p);
return 0;

}

void foo(int r){
int s=r+1;
p=&s;

}

int baz(int r) {
int t=19;
int k=4;

return t + k + t;
}

This prints:
[tmp]$ ./a.out
0xfee768a4 19

Aug 23 '06 #3
Sourav wrote:
>
Suppose I have a code like this,

#include <stdio.h>

int *p;
void foo(int);

int main(void){
foo(3);
printf("%p %d\n",p,*p);
return 0;
}

void foo(int r){
int s=r+1;
p=&s;
}

In most of the compilers I use (GCC, MSVC++, lcc..) this program
runs allright printing an address and the correct value 4. But is
it correct to assign a global pointer the address of a local
variable which does not exist after the function has ended?
It is correct to assign it. It is not correct to use it after the
function has exited.

--
Chuck F (cb********@yah oo.com) (cb********@mai neline.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.netUSE maineline address!

Aug 23 '06 #4
On Wed, 23 Aug 2006 06:32:54 GMT, Keith Thompson <ks***@mib.or g>
wrote:
>"Sourav" <so*********@gm ail.comwrites:
>Suppose I have a code like this,

#include <stdio.h>

int *p;
void foo(int);

int main(void){
foo(3);
printf("%p %d\n",p,*p);
return 0;
}

void foo(int r){
int s=r+1;
p=&s;
}

In most of the compilers I use (GCC, MSVC++, lcc..) this program runs
allright printing an address and the correct value 4. But is it correct
to assign a global pointer the address of a local variable which does
not exist after the function has ended?

No, it isn't. When s reaches the end of its lifetime (at the end of
foo(), the value of p becomes indeterminate. Dereferencing p, or even
looking at its value, invokes undefined behavior. (The latter isn't
likely to cause any visible problems on most systems, but you should
still avoid it.)
The word "looking" is vague. Does it mean that I can't do something
like this?

#include <stdio.h>

static int* foo(void);

int main(void)
{
int *p;
p = foo();/* legal? */
printf("Pointer was %p\n", (void*)p);/* legal? */
return 0;
}

static int* foo(void)
{
int i;
return &i;
}

--
jay
Aug 23 '06 #5
jaysome <ja*****@spamco p.netwrites:
On Wed, 23 Aug 2006 06:32:54 GMT, Keith Thompson <ks***@mib.or g>
wrote:
[...]
>>No, it isn't. When s reaches the end of its lifetime (at the end of
foo(), the value of p becomes indeterminate. Dereferencing p, or even
looking at its value, invokes undefined behavior. (The latter isn't
likely to cause any visible problems on most systems, but you should
still avoid it.)

The word "looking" is vague. Does it mean that I can't do something
like this?

#include <stdio.h>

static int* foo(void);

int main(void)
{
int *p;
p = foo();/* legal? */
printf("Pointer was %p\n", (void*)p);/* legal? */
return 0;
}

static int* foo(void)
{
int i;
return &i;
}
Any reference to the value of p after foo() returns invokes undefined
behavior. For that matter, I think assigning the result of foo() to p
in the first place invokes UB.

--
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.
Aug 23 '06 #6
Keith Thompson wrote:
>
"Sourav" <so*********@gm ail.comwrites:
Suppose I have a code like this,
[... code which stores &localvar in globalvar ...]

In most of the compilers I use (GCC, MSVC++, lcc..) this program runs
allright printing an address and the correct value 4. But is it correct
to assign a global pointer the address of a local variable which does
not exist after the function has ended?

No, it isn't. When s reaches the end of its lifetime (at the end of
foo(), the value of p becomes indeterminate. Dereferencing p, or even
looking at its value, invokes undefined behavior. (The latter isn't
likely to cause any visible problems on most systems, but you should
still avoid it.)
<mode pedant=on>

"To assign a global variable the address of a local variable" is fine.
It's the use of that variable after the function exits that is UB.

</mode>

Imagine a situation where the function calls other functions which use
the global variable. This is not a problem. (Well, some people would
argue that it's a "problem" in the sense that "you shouldn't use global
variables". But that's a different issue entirely.)

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Aug 23 '06 #7
Keith Thompson wrote:
jaysome <ja*****@spamco p.netwrites:
>On Wed, 23 Aug 2006 06:32:54 GMT, Keith Thompson <ks***@mib.or g>
wrote:
[...]
>>>No, it isn't. When s reaches the end of its lifetime (at the end of
foo(), the value of p becomes indeterminate. Dereferencing p, or even
looking at its value, invokes undefined behavior. (The latter isn't
likely to cause any visible problems on most systems, but you should
still avoid it.)

The word "looking" is vague. Does it mean that I can't do something
like this?

#include <stdio.h>

static int* foo(void);

int main(void)
{
int *p;
p = foo();/* legal? */
printf("Pointer was %p\n", (void*)p);/* legal? */
return 0;
}

static int* foo(void)
{
int i;
return &i;
}

Any reference to the value of p after foo() returns invokes undefined
behavior. For that matter, I think assigning the result of foo() to p
in the first place invokes UB.
A question: what about just "foo();" (without an assignment)? Is the value
allowed to be read before discarding it?
Aug 23 '06 #8
>But is it correct
to assign a global pointer the address of a local variable which does
not exist after the function has ended?
Imagine yesterday you went to a motel and asked for a room. The guy at
the counter says "no problem, I'll give you room 0x00244528" (this is a
big motel). You and your "date", Quadrophenia, go up to the room and
have a good old time. Reading the Bible, that is.

The next morning you exit the motel, but you take the door key wiith
you.

Now the $50,000 question: Is it likely you can go back to the motel
the next year, open the door to room 0x00244528, and find Quadrophenia
there?

Aug 23 '06 #9
"Ancient_Hacker " <gr**@comcast.n etwrites:
>>But is it correct
to assign a global pointer the address of a local variable which does
not exist after the function has ended?
The above was posted by Sourav <so*********@gm ail.com>. Please don't
snip attributions.
Imagine yesterday you went to a motel and asked for a room. The guy at
the counter says "no problem, I'll give you room 0x00244528" (this is a
big motel). You and your "date", Quadrophenia, go up to the room and
have a good old time. Reading the Bible, that is.

The next morning you exit the motel, but you take the door key wiith
you.

Now the $50,000 question: Is it likely you can go back to the motel
the next year, open the door to room 0x00244528, and find Quadrophenia
there?
Now the $51,000 question. After you've checked out, can you even
*look* at the key? In the motel key analogy, of course you can; in C,
accessing the value of the pointer (without even dereferencing it /
using it to open the door) invokes undefined behavior.

Sticking to the the motel key model, if you take the key to a
locksmith to have it duplicated, the locksmith *might* recognize that
you've checked out of the room and refuse to duplicate it, or even
call the police (who will then make demons fly out of your nose).

--
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.
Aug 23 '06 #10

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

Similar topics

7
2640
by: NS Develop | last post by:
What's wrong with the following: void SomeClass::someMethod(void) { A *ptrA = NULL; ptrA = &A(); .... }
18
2919
by: Xiangliang Meng | last post by:
Hi. void setValue(int n) { int size = getValueLength(); int buffer_p; if (buffer_p) { ....
2
2681
by: Kench | last post by:
I was curious and playing with pointers and references to see what's different between them. Other than the obvious ones involving C++ syntax & things like references cannot be modified with addition & subtraction, pointers can be modified, both are similar. It stated me going what are the diferrence between a reference vairable and local...
2
1351
by: Chris Stankevitz | last post by:
Hi, I have some weird behavior in a very large (500,000 line) program that I boiled down to a few lines: TCSensorMode::ProcessMeasurement() { InternalComplicatedFunction(1.0, 2.0); int a = abs(1); int b = abs(1);
4
11337
by: octavio | last post by:
Hello members of the comp.lang.c newsgroup. Please I need you help on the following one. Compiling the simple code I'm getting this error message. Why ? Please what's the correct type of the fb function ? Thank You. Octavio and.c:15: attention : type mismatch with previous implicit declaration and.c:11: attention : previous implicit...
31
17667
by: leonm54 | last post by:
I remember that this is a bad practice, but can not find a definitive resource that states it is bad and why. Can anyone help?
14
16146
by: Spitfire | last post by:
Hi All, I've this weird question about pointers. I would like to know how to return the address of a local variable, safely!! Isn't that a unrecommended procedure? Doesn't it have possibilities that the variable could be deallocated from memory and the dereferencing of the returned pointer somewhere else could crash the program? If it's not...
3
2713
by: ali | last post by:
Hi, When I pass a pointer as an argument of a method, is it safe if I change the data pointed by the argument and return it upon completion ? For example: Object* someFunction(Object* ob) {
13
13165
by: hari | last post by:
Hi all, Is it legal to return a local variable from function. Regards Hari
0
7490
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...
0
7682
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. ...
0
7935
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...
0
6009
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...
1
5351
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...
0
3479
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...
0
3465
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1037
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
734
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...

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.