473,406 Members | 2,312 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,406 software developers and data experts.

returning address of stack variable

Hi All,

The following code as per my knowledge should not work:

int* some()
{
int b = 10;
return &b;
}
int main(int argc, char** argv)
{
int* test = NULL;

test = some();
printf("test ; %d\n", *test);
*test = 20;

return 0;
}

as it is returning the address of a variable on stack which should not
be valid once the function returns. However, this code seems to be
working absolutely fine in VC++ 6.0 on x86 processor. Could anyone
please explain what is correct or wrong and why is it working.

Also, in the following statement
char *p = "Hello world";
where is the memory for p allocated? is it on stack, heap or global
area and when is it freed, if so?

Thanks in advance,
Manish

May 11 '06 #1
19 3069
Manish Tomar wrote:
Hi All,

The following code as per my knowledge should not work:

int* some()
{
int b = 10;
return &b;
}
int main(int argc, char** argv)
{
int* test = NULL;

test = some();
printf("test ; %d\n", *test);
*test = 20;

return 0;
}

as it is returning the address of a variable on stack which should not
be valid once the function returns. However, this code seems to be
working absolutely fine in VC++ 6.0 on x86 processor. Could anyone
please explain what is correct or wrong and why is it working.
You have undefined behaviour. The value is still valid because nothing
has had a chance to overwrite it. Add a couple more function calls
before the printf and see what happens.
Also, in the following statement
char *p = "Hello world";
where is the memory for p allocated? is it on stack, heap or global
area and when is it freed, if so?

It isn't, "Hello world" is a string literal, look it up in the FAQ.

--
Ian Collins.
May 11 '06 #2
Manish Tomar said:
Hi All,

The following code as per my knowledge should not work:


And it doesn't. Unfortunately, "not work" can have a variety of outcomes.
One of those outcomes is "what someone who thinks the code is correct would
expect to happen, up until the cost of it not working exceeds the value of
continuing to hire the person writing the code".

In other words, the code will continue to work until your boss is
demonstrating the program to an important customer, at which point it will
fail in a highly visible and embarrassing way.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
May 11 '06 #3
In statement printf("Hello world"), the printf function receives the
string literal as char* which means it receives some memory address.
Hence some memory should be used to store this string. Where is it?

May 11 '06 #4
Manish Tomar wrote:

In statement printf("Hello world"), the printf function receives the
string literal as char* which means it receives some memory address.
Hence some memory should be used to store this string. Where is it?


printf("It's at %p\n", (void *)"Hello world");

--
pete
May 11 '06 #5

pete wrote:
Manish Tomar wrote:

In statement printf("Hello world"), the printf function receives the
string literal as char* which means it receives some memory address.
Hence some memory should be used to store this string. Where is it?


printf("It's at %p\n", (void *)"Hello world");


IMHO, the OP was looking for stack/heap as an answer. Which of course
if one of the most commonly occuring questions around here.I remember
having read a rather excellent post by Mr. Paul Hsieh regarding this,
sometime
back.STFW.

May 11 '06 #6
"Suman" <sk*****@gmail.com> wrote:
pete wrote:
Manish Tomar wrote:

In statement printf("Hello world"), the printf function receives the
string literal as char* which means it receives some memory address.
Hence some memory should be used to store this string. Where is it?
printf("It's at %p\n", (void *)"Hello world");


IMHO, the OP was looking for stack/heap as an answer. Which of course
if one of the most commonly occuring questions around here.


The question misses the point; and any definite answer is likely to be
unreliable.
(FWIW, any string literal has static duration; the most logical place to
put them where they occur normally is neither on the stack nor on what
is inaccurately termed the heap; but this is a function parameter, so
putting _this_ string literal where normal function parameters are
passed is also a viable option; other options are not inconceivable; and
most importantly, any program which cares the slightest _where_ string
literals reside is designed broken.)
I remember having read a rather excellent post by Mr. Paul Hsieh regarding
this, sometime back.


I would be most surprised.

Richard
May 11 '06 #7
Manish Tomar wrote:
In statement printf("Hello world"), the printf function receives the
string literal as char* which means it receives some memory address.
Hence some memory should be used to store this string. Where is it?


Where ever the implementation chooses to store it. On a number of the
systems I've dealt with it would be burnt in to an EEPROM, but this is
slightly less likely on a desktop PC.

All you need to know is that the string exists for the lifetime of the
program.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc

Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php
May 11 '06 #8
Suman wrote:

pete wrote:
Manish Tomar wrote:

In statement printf("Hello world"),
the printf function receives the
string literal as char* which means it
receives some memory address.
Hence some memory should be
used to store this string. Where is it?


printf("It's at %p\n", (void *)"Hello world");


IMHO, the OP was looking for stack/heap as an answer.


"The stack" and "the heap"
aren't part of the C programming language.

--
pete
May 11 '06 #9

pete wrote:
Suman wrote:

[...]
IMHO, the OP was looking for stack/heap as an answer.


"The stack" and "the heap"
aren't part of the C programming language.


Of course not, which is why I avoided any allusion to them in
my reply. I somehow missed the whole thread, and now that
I have it, I do see that the OP _did_ mention stack/heap etc
in early on.

The problem is your reply is technically sound and correct.
But I have a gut feeling it fails to communicate with the OP.
Whence my lament.

May 11 '06 #10
In article <11*********************@i39g2000cwa.googlegroups. com>,
Manish Tomar <ma**********@gmail.com> wrote:
In statement printf("Hello world"), the printf function receives the
string literal as char* which means it receives some memory address.
Hence some memory should be used to store this string. Where is it?


Amongst the possible answers, the choice of which will depend upon
the OS, the processor, memory hardware, and the compiler flags:

- ROM
- EEPROM
- discrete memory "buffers"
- hardware synthesized without anything recognizable as "storage"
- punched cards
- "core" memory
- punch tape
- magnetic tape
- mercury acoustic delay line memory
(http://en.wikipedia.org/wiki/Mercury_delay_line)
- "bubble memory"
- laser disc swapped into memory at need
- CD-ROM swapped into memory at need
- memory-mapped magnetic harddrive
- memory marked by the memory controller as "read only"
- FPGAs
- embedded in the generated executable code
- from a memory-mapped copy of the executable, swapped in at need
- created by the code "on the fly" and stored on the stack or heap or
some other convenient location
- microcoded into the processor (yes, seriously -- for example, the
empty string is easy to microcode)
- 2D and 3D holograms

This list is not meant to be exhaustive!
--
There are some ideas so wrong that only a very intelligent person
could believe in them. -- George Orwell
May 11 '06 #11
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
"Suman" <sk*****@gmail.com> wrote:
pete wrote:
> Manish Tomar wrote:
> >
> > In statement printf("Hello world"), the printf function receives the
> > string literal as char* which means it receives some memory address.
> > Hence some memory should be used to store this string. Where is it?
>
> printf("It's at %p\n", (void *)"Hello world");


IMHO, the OP was looking for stack/heap as an answer. Which of course
if one of the most commonly occuring questions around here.


The question misses the point; and any definite answer is likely to be
unreliable.
(FWIW, any string literal has static duration; the most logical place to
put them where they occur normally is neither on the stack nor on what
is inaccurately termed the heap; but this is a function parameter, so
putting _this_ string literal where normal function parameters are
passed is also a viable option; other options are not inconceivable; and
most importantly, any program which cares the slightest _where_ string
literals reside is designed broken.)

[...]

Actually, the fact that the address of the string literal is passed as
an argument to a function *doesn't* mean that the compiler can store
the string literal itself where normal function parameters are stored.
The function could save the address in a statically allocated
variable, and other functions could examine it after the original
function has completed. If that address no longer points to a string
with the value "Hello world", you have a non-conforming
implementation.

If the compiler happens to know that this specific function doesn't do
that (as it might legitimately assume for printf()), it can do
something like this. I seriously doubt that it would be worth the
effort. After all, the string would have to be copied from somewhere
into the parameter; it's simpler to just pass the address of wherever
it is originally.

--
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.
May 11 '06 #12
"Manish Tomar" <ma**********@gmail.com> wrote in message
news:11**********************@u72g2000cwu.googlegr oups.com...
Hi All,

The following code as per my knowledge should not work:

int* some()
{
int b = 10;
return &b;
}


This invokes undefined behavior. After this, your program can do anything
it wants to, including (but not limited to) exactly what you expect it to
do. It could also do the opposite, but Murphy's Law says that won't happen
until the worst possible moment, i.e. when demoing your product to a
critical customer.

Please note that C doesn't define a "stack"; that's an implementation detail
(though a common way of handling automatic variables).

S

--
Stephen Sprunk "Stupid people surround themselves with smart
CCIE #3723 people. Smart people surround themselves with
K5SSS smart people who disagree with them." --Aaron Sorkin
*** Posted via a free Usenet account from http://www.teranews.com ***
May 11 '06 #13
Suman wrote:
pete wrote:
Manish Tomar wrote:
In statement printf("Hello world"), the printf function receives the
string literal as char* which means it receives some memory address.
Hence some memory should be used to store this string. Where is it?


printf("It's at %p\n", (void *)"Hello world");


IMHO, the OP was looking for stack/heap as an answer. Which of course
if one of the most commonly occuring questions around here.I remember
having read a rather excellent post by Mr. Paul Hsieh regarding this,
sometime
back.STFW.


Oooh! A groupie! :) You may be referring to this post:

http://groups.google.com/group/comp....53d96db7dad45c

But in general, an inline string, (or "string literal") has implicit
static storage (in some section of memory similar to other statics,
except that you cannot write to it) unless it is used as an
initiailizer to a variable with its own declared storage. In this case
there is no declaration, so you can treat it as if it were some static
object.

(And BTW, its neither on the stack or the heap.)

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

May 12 '06 #14
pete wrote:
Suman wrote:
pete wrote:
Manish Tomar wrote:
> In statement printf("Hello world"),
> the printf function receives the
> string literal as char* which means it
> receives some memory address.
> Hence some memory should be
> used to store this string. Where is it?

printf("It's at %p\n", (void *)"Hello world");


IMHO, the OP was looking for stack/heap as an answer.


"The stack" and "the heap"
aren't part of the C programming language.


This is probably true in exactly the same way that Keith thinks that
variables are not part of the C programming language (i.e., not at all
except that maybe you can't grep for it in the standard.)

Both, of course, are extremely well defined concepts and referring to
them directly is valuable and important in the ordinary discourse of
programming, especially in the C language.

Perhaps you are confused because there is both a call stack, and an
auto-stack, which may or may not be intertwined depending on the
implementation (though even this detail is technically irrelevant since
the two stacks are synchronized), and the fact that one prominant
implementation has a hardware stack called "the stack" (leading you to
the false dichotomy of "since an implementation refers to it, it must
not be meaningful in the language of the standard"). But the fact is,
function calls and their corresponding returns behave exactly with
stack-like semantics (even longjmp really does nothing more than
mutiple pops at once.) This analogy isn't far fetched -- its
stack-like semantics is what helps you understand how it works.

I have no idea what your problem with the heap is. The fact is that
heap allocations are distinct and independent from the stack and
static/global storage. (In particular, the lifetime of a heap
allocation is dictated arbitrarily by runtime program semantics.) But
this is obvious -- so I don't know what you problem is.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

May 12 '06 #15
we******@gmail.com wrote:
Suman wrote:

[ ...]
I remember
having read a rather excellent post by Mr. Paul Hsieh regarding this,
sometime
back.STFW.


Oooh! A groupie! :) You may be referring to this post:

http://groups.google.com/group/comp....53d96db7dad45c


This is the one I had in my mind though :)
<url:
http://groups.google.com/group/comp....bfb8bef9cad3f1 >

I thought this was more in tune with the spirit of the OP's question.

Thanks all the same for coming to aid of my sieve like memory!

May 12 '06 #16
we******@gmail.com wrote:

pete wrote:
Suman wrote:
pete wrote:
> Manish Tomar wrote:
> > In statement printf("Hello world"),
> > the printf function receives the
> > string literal as char* which means it
> > receives some memory address.
> > Hence some memory should be
> > used to store this string. Where is it?
>
> printf("It's at %p\n", (void *)"Hello world");

IMHO, the OP was looking for stack/heap as an answer.
"The stack" and "the heap"
aren't part of the C programming language.


This is probably true in exactly the same way that Keith thinks that
variables are not part of the C programming language (i.e., not at all
except that maybe you can't grep for it in the standard.)


Inapt analogy: You can grep on "variables" in the standard.
Both, of course, are extremely well defined concepts
So is my keyboard. I use a Lexmark Model M. It's the best!
and referring to
them directly is valuable and important in the ordinary discourse of
programming,
Try news:comp.programming
especially in the C language.


You do not ever need to have heard of the "stack and the heap"
to write a conforming C program.

--
pete
May 12 '06 #17
pete said:
we******@gmail.com wrote:

This is probably true in exactly the same way that Keith thinks that
variables are not part of the C programming language (i.e., not at all
except that maybe you can't grep for it in the standard.)


Inapt analogy: You can grep on "variables" in the standard.


You won't get any hits, though. Well, I didn't, in the C89 draft. Searching
for the singular, "variable", gave me 23 hits, most of which were to do
with variable argument lists. But I did find these:

"the ``integral promotions'' require that the abstract machine promote
the value of each variable to int size and then add the two int s and
truncate the sum." (referring to a couple of char objects) - 2.1,
non-normative example

"Therefore, for full portability the variable c should be declared as int."
- 3.3.16.1, non-normative example

"The following pair of declarations demonstrates the difference
between a ``variable pointer to a constant value'' and a ``constant
pointer to a variable value.''" - 3.5.4.1, non-normative example

"...assigning a value to a static storage duration variable of type volatile
sig_atomic_t" - 4.7.1.1 - normative text.

"an enumeration variable that has the same type" - A.5, non-normative
appendix

I think the normative text of 4.7.1.1 shows that "variable" is indeed a C
concept. It's a shame, in a way, since it's such a woolly term. Did this
usage in 4.7.1.1 survive into the final C89 standard?
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
May 12 '06 #18
CoL
Here p has not allocated any memory rather points a chunk of memory
which by ANSI C standard is "Constant static character literal".
When you define char *p = "Hello world";
"Hello world" follows the above mentioned rule.
Now since its static in nature so should be a part of "data Section,
rather than Stack Or Heap.So you can very much return its address from
a fuction as its static by nature.
E.g had it been
char buff[20]="Hello world"; then you cant return its address from
fuction since now its a part of stack local to the function.
I hope you find this helpful.

Regards,
COL



Ian Collins wrote:
Manish Tomar wrote:
Hi All,

The following code as per my knowledge should not work:

int* some()
{
int b = 10;
return &b;
}
int main(int argc, char** argv)
{
int* test = NULL;

test = some();
printf("test ; %d\n", *test);
*test = 20;

return 0;
}

as it is returning the address of a variable on stack which should not
be valid once the function returns. However, this code seems to be
working absolutely fine in VC++ 6.0 on x86 processor. Could anyone
please explain what is correct or wrong and why is it working.

You have undefined behaviour. The value is still valid because nothing
has had a chance to overwrite it. Add a couple more function calls
before the printf and see what happens.
Also, in the following statement
char *p = "Hello world";
where is the memory for p allocated? is it on stack, heap or global
area and when is it freed, if so?

It isn't, "Hello world" is a string literal, look it up in the FAQ.

--
Ian Collins.


May 12 '06 #19
Richard Heathfield wrote:

pete said:
we******@gmail.com wrote:

This is probably true in exactly the same way that
Keith
thinks that variables are not part of the C programming language
(i.e., not at all
except that maybe you can't grep for it in the standard.)


Inapt analogy: You can grep on "variables" in the standard.


You won't get any hits, though.
Well, I didn't, in the C89 draft. Searching
for the singular, "variable", gave me 23 hits,
most of which were to do
with variable argument lists. But I did find these:

"the ``integral promotions'' require that the abstract machine promote
the value of each variable to int size and then add the two int s and
truncate the sum." (referring to a couple of char objects) - 2.1,
non-normative example

"Therefore, for full portability the variable
c should be declared as int."
- 3.3.16.1, non-normative example

"The following pair of declarations demonstrates the difference
between a ``variable pointer to a constant value'' and a ``constant
pointer to a variable value.''" - 3.5.4.1, non-normative example

"...assigning a value to a static storage
duration variable of type volatile
sig_atomic_t" - 4.7.1.1 - normative text.

"an enumeration variable that has the same type" - A.5, non-normative
appendix

I think the normative text of 4.7.1.1
shows that "variable" is indeed a C
concept. It's a shame, in a way, since it's such a woolly term.
Did this
usage in 4.7.1.1 survive into the final C89 standard?


Yes, they all survived.
C99 has the word "variables".

--
pete
May 12 '06 #20

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

Similar topics

17
by: Roland Hall | last post by:
Is there a way to return multiple values from a function without using an array? Would a dictionary object work better? -- Roland Hall /* This information is distributed in the hope that it...
3
by: Milan Gornik | last post by:
Hello to all, My question is on right way of returning newly created class from a function (and thus, from class method or operator). As I currently see it, there are two different ways to...
1
by: john | last post by:
Relatively new to C coding, so any help would greatly be appreciated. I'm having problems try to return my string array from my parsing function. When I do a printf I am getting the correct value...
7
by: wonderboy | last post by:
Hey guys, I have a simple question. Suppose we have the following functions:- //-----My code starts here char* f1(char* s) { char* temp="Hi"; return temp;
6
by: Generic Usenet Account | last post by:
Is it okay to return a local datastructure (something of type struct) from a function, as long as it does not have any pointer fields? I think it is a bad idea, but one of my colleagues does not...
17
by: I.M. !Knuth | last post by:
Hi. I'm more-or-less a C newbie. I thought I had pointers under control until I started goofing around with this: ...
4
by: rsa_net_newbie | last post by:
Hi there, I have a Managed C++ object (in a DLL) which has a method that is defined like ... Generic::List<String^>^ buildList(String^ inParm) Now, when I compile it, I get "warning C4172:...
6
by: student1976 | last post by:
All Beginner/Intermediate level question. I understand that returning ptr to local stack vars is bad. Is returning foo_p_B from fnB() reliable all the time, so that using foo_p_A does not...
160
by: DiAvOl | last post by:
Hello everyone, Please take a look at the following code: #include <stdio.h> typedef struct person { char name; int age; } Person;
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...
0
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,...
0
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...

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.