473,797 Members | 3,152 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

return address of string from a function

Hi Everyone,

I have the following function,

char* sample1()
{
char *p = "india";
return(p);
}

//in this case the memory storing india is not destroyed at the end
of the function, indicating that it wasn't stored in the stack meant
for the function call.

However, the following function causes unexpected behavior as
expected ;-)

char* sample2()
{
char p[] = "india";
return(p);
}

I tried both the functions in Microsoft Visual C++ 6.0, is it
specified as per the standard that the first case be not stored in the
stack or is it implementation defined?

Thanks in advance!!!

May 4 '07 #1
3 5881
In article <11************ **********@h2g2 000hsg.googlegr oups.com>,
<sa*****@yahoo. co.inwrote:
I have the following function,
char* sample1()
{
char *p = "india";
return(p);
}
//in this case the memory storing india is not destroyed at the end
of the function, indicating that it wasn't stored in the stack meant
for the function call.
>However, the following function causes unexpected behavior as
expected ;-)
>char* sample2()
{
char p[] = "india";
return(p);
}
I tried both the functions in Microsoft Visual C++ 6.0, is it
specified as per the standard that the first case be not stored in the
stack or is it implementation defined?
In the first case, you are setting the local variable p to point
to the string literal "india". The C standard says that all
string literals will live throughout the execution of the program.
String literals are allowed to be read-only.

In the second case, although the syntax looks so close, you are
instead setting a local variable to point to some automatic
storage space that is initialized to {'i','n','d','i ','a',0} .
This is not a string literal, and the space reserved is not
read-only.

Note, by the way, that the C standard says nothing about stacks;
there are implementations that don't use stacks as you know them.
The C standard talks of automatic storage and of variable lifetimes,
without saying how exactly these things are achieved.
--
"It is important to remember that when it comes to law, computers
never make copies, only human beings make copies. Computers are given
commands, not permission. Only people can be given permission."
-- Brad Templeton
May 4 '07 #2
sa*****@yahoo.c o.in wrote On 05/04/07 16:29,:
Hi Everyone,

I have the following function,

char* sample1()
{
char *p = "india";
return(p);
}

//in this case the memory storing india is not destroyed at the end
of the function, indicating that it wasn't stored in the stack meant
for the function call.
Correct. The nameless array holding the characters
of "india" has what is called "static storage duration,"
just like variables declared with the `static' keyword.
All static objects already exist and have been initialized
when main() is first called, and continue to exist until
the program ends.
However, the following function causes unexpected behavior as
expected ;-)
"Expect the unexpected." Difficult advice to follow,
and probably not the best advice for programmers. They
would do better to "Avoid the unexpected."
char* sample2()
{
char p[] = "india";
return(p);
}
This is perfectly legal! There is, however, one tiny
gotcha: Undefined behavior occurs if the caller makes any
use whatever of the value returned by sample2(). Trying
to call `puts(sample2() ()' is obviously off limits, but so
are seemingly harmless uses like `ptr = sample2()' and
`if (sample2() == NULL)'. Only `(void)sample2( )' (or an
equivalent) is safe.

Details: The array p[] has "automatic storage duration,"
which lasts from the moment execution enters its block to
the moment execution exits the block. As soon as the block
that is the body of sample2() exits -- at the `return' --
the array p[] ceases to exist, and any pointer that formerly
pointed to any element of p[] has an indeterminate value.
Using an indeterminate value causes undefined behavior.
I tried both the functions in Microsoft Visual C++ 6.0, is it
specified as per the standard that the first case be not stored in the
stack or is it implementation defined?
The implementation decides where to store "india" and
p[]; the Standard has nothing to say about it (the Standard
doesn't even mention "the stack"). Instead, the Standard
specifies the required lifetimes of the various kinds of
objects. The implementation must arrange for the correct
lifetimes, but can do so in any way it pleases.

--
Er*********@sun .com
May 4 '07 #3
ro******@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes:
In article <11************ **********@h2g2 000hsg.googlegr oups.com>,
<sa*****@yahoo. co.inwrote:
>I have the following function,
>char* sample1()
{
char *p = "india";
return(p);
}
>//in this case the memory storing india is not destroyed at the end
of the function, indicating that it wasn't stored in the stack meant
for the function call.
>>However, the following function causes unexpected behavior as
expected ;-)
>>char* sample2()
{
char p[] = "india";
return(p);
}
>I tried both the functions in Microsoft Visual C++ 6.0, is it
specified as per the standard that the first case be not stored in the
stack or is it implementation defined?

In the first case, you are setting the local variable p to point
to the string literal "india". The C standard says that all
string literals will live throughout the execution of the program.
String literals are allowed to be read-only.

In the second case, although the syntax looks so close, you are
instead setting a local variable to point to some automatic
storage space that is initialized to {'i','n','d','i ','a',0} .
This is not a string literal, and the space reserved is not
read-only.
A quibble: the local variable in sample2(), named "p", doesn't point
to anything. It's an array, not a pointer. (When the name of the
array is used in the return statement, it's implicitly converted to a
pointer value.)
Note, by the way, that the C standard says nothing about stacks;
there are implementations that don't use stacks as you know them.
The C standard talks of automatic storage and of variable lifetimes,
without saying how exactly these things are achieved.
--
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."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
May 4 '07 #4

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

Similar topics

3
4530
by: Phil Powell | last post by:
My first time working with a PHP class, and after 6 hours of working out the kinks I am unable to return a value from the class, so now I appeal to the general audience what on earth did I do wrong this time? This is the code the retrieves the values: if (($hasRegistered || $hasPreRegistered) && !empty($uplinenumber)) { // CHECK TO SEE IF UPLINE NUMBER IS A VALID NUMBER $regNumberGenerator = new RegNumberGenerator($uplinenumber,...
8
2373
by: John Smith | last post by:
Hi, I'm writing a library in C++ which is supposed to be used by people using C. One function I have must return a string to users which is arbitrary length. The user must be able to use this string as "char *" so I was wondering if the following construct is safe: char *Func() { static string str;
19
11192
by: Sergey Koveshnikov | last post by:
Hello, If my function return a pointer on a memory area, where do I free it? e.x.: char *foo() { char *p; p = malloc(10); strcpy(p, "something"); return(p); }
23
3615
by: Nascimento | last post by:
Hello, How to I do to return a string as a result of a function. I wrote the following function: char prt_tralha(int num) { int i; char tralha;
7
1844
by: MLH | last post by:
?dcount("","qryOwnrsDueITSwMissingAddr") when run in the immediate window return a number greater than the number of rows that display when the saved query is run - opening in the database window? I consistently see 2 rows in qryOwnrsDueITSwMissingAddr opening with a dbl-clik. Yet ?dcount("","qryOwnrsDueITSwMissingAddr") returns 3 and
22
3261
by: Michael Rasmussen | last post by:
Hi all, Not sure if this is OT? I have a function in a library written in C++ which returns a strdup(s.c_str()) to an application written i C. Running Valgrind on my C-application shows this results in memory leaks due to the c_str is never freed. Example:
18
4066
by: Pedro Pinto | last post by:
Hi there once more........ Instead of showing all the code my problem is simple. I've tried to create this function: char temp(char *string){ alterString(string); return string;
10
5620
by: Raj | last post by:
I need a VB function to return array of collections like Private Type Employee empname as string address as string salary as integer deptno as integer End Type dim employees() as Employee
3
3015
by: jambonjamasb | last post by:
Hi I have two tables: email_tbl Data_table Data table is is used to create a Form Data_form
10
4398
by: Mikhail Kovalev | last post by:
Suppose I have something like this $resource = curl_init(); curl_setopt($resource, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($resource, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($resource, CURLOPT_URL, '......'); curl_exec($resource); $lastUrl = curl_getinfo($resource, CURLINFO_EFFECTIVE_URL); curl_close($resource);
0
9685
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
10246
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...
0
10023
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
9066
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...
1
7560
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
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4135
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
3750
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2934
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.