473,387 Members | 1,520 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,387 software developers and data experts.

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 5867
In article <11**********************@h2g2000hsg.googlegroups. 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.co.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.nrc-cnrc.gc.ca (Walter Roberson) writes:
In article <11**********************@h2g2000hsg.googlegroups. 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_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."
-- 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
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...
8
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...
19
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
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
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?...
22
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...
18
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
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
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
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,...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...

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.