473,765 Members | 2,021 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is it legal to return a local variable from function.

Hi all,
Is it legal to return a local variable from function.

Regards
Hari

Nov 19 '07 #1
13 13204
In article <95************ *************** *******@d27g200 0prf.googlegrou ps.com>,
hari <ha********@gma il.comwrote:
>Is it legal to return a local variable from function.
You'll have to be more specific. You can't return variables, only
values. You can certainly return the value of a local variable. You
can't safely return a pointer to a local variable, because it won't
exist after the return.

-- Richard

--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Nov 19 '07 #2
In article
<95************ *************** *******@d27g200 0prf.googlegrou ps.com>,
hari <ha********@gma il.comwrote on Monday 19 Nov 2007 4:57 pm:
Hi all,
Is it legal to return a local variable from function.
Yes. Returning a pointer to it however is dangerous unless the said
local is static.

Nov 19 '07 #3
On Nov 19, 4:34 pm, santosh <santosh....@gm ail.comwrote:
In article
<952875bd-9cc5-4cac-8ade-6fa37cdb4...@d2 7g2000prf.googl egroups.com>,
hari <haricib...@gma il.comwrote on Monday 19 Nov 2007 4:57 pm:
Hi all,
Is it legal to return a local variable from function.

Yes. Returning a pointer to it however is dangerous unless the said
local is static.
Well, I have a doubt. If I allocate memory for a local pointer and
return the address of the pointer to the calling function. Now will
this be dangerous. For eg:

int main()
{
char *test(int i);
char *tmp = NULL;
int i = 10;
tmp = test(i);
printf("%s\n", tmp);
free(tmp);
return 0;
}

char *test(int i)
{
char *str = (char*)malloc(2 0);
sprintf(str, "i value is: %d", i);
return str;
}
Nov 19 '07 #4
"arunmib" <ar*****@gmail. comschrieb im Newsbeitrag
news:83******** *************** ***********@w28 g2000hsf.google groups.com...
On Nov 19, 4:34 pm, santosh <santosh....@gm ail.comwrote:
>In article
<952875bd-9cc5-4cac-8ade-6fa37cdb4...@d2 7g2000prf.googl egroups.com>,
hari <haricib...@gma il.comwrote on Monday 19 Nov 2007 4:57 pm:
Hi all,
Is it legal to return a local variable from function.

Yes. Returning a pointer to it however is dangerous unless the said
local is static.

Well, I have a doubt. If I allocate memory for a local pointer and
return the address of the pointer to the calling function. Now will
this be dangerous. For eg:

int main()
{
char *test(int i);
char *tmp = NULL;
int i = 10;
tmp = test(i);
printf("%s\n", tmp);
free(tmp);
return 0;
}

char *test(int i)
{
char *str = (char*)malloc(2 0);
sprintf(str, "i value is: %d", i);
return str;
}
In this case it is save to return *str. It is unsafe though to a) cast the
result of the malloc, b) not check whether it succeededs and then writing to
/ read from the unchecked result, c) pass an int to that function that
requires more than 7 characters in decimal

Bye, Jojo
Nov 19 '07 #5
arunmib said:

<snip>
Well, I have a doubt. If I allocate memory for a local pointer and
return the address of the pointer to the calling function. Now will
this be dangerous. For eg:

int main()
{
char *test(int i);
char *tmp = NULL;
int i = 10;
tmp = test(i);
printf("%s\n", tmp);
free(tmp);
return 0;
}

char *test(int i)
{
char *str = (char*)malloc(2 0);
sprintf(str, "i value is: %d", i);
return str;
}
First, the bugs. You forgot to #include <stdlib.hand <stdio.h- your
compiler would certainly have warned you that something was amiss, if only
you hadn't silenced it with a useless cast. You assume without
justification that the memory allocation request succeeded.

Okay, now to your question.

You haven't allocated any memory "for a local pointer". You've allocated
some memory, full stop. When you do so, you are given a value, which you
can use for referring to that memory. It's a pointer value (which points
to the beginning of the memory you've allocated). You have stored that
pointer value into a pointer object, which is a very right and proper
thing to do.

You have then returned that value, the value of the pointer object, to the
calling function. You have *not* returned the str object, merely its
value, which - if you will recall - points to the beginning of the memory
you allocated. That's absolutely fine, because that memory you allocated
via malloc (if indeed it succeeded at all) will continue to exist until
you explicitly release it by passing that pointer value to free().

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Nov 19 '07 #6
Joachim Schmitz said:
"arunmib" <ar*****@gmail. comschrieb im Newsbeitrag
<snip>
>>
int main()
{
char *test(int i);
char *tmp = NULL;
int i = 10;
tmp = test(i);
printf("%s\n", tmp);
free(tmp);
return 0;
}

char *test(int i)
{
char *str = (char*)malloc(2 0);
sprintf(str, "i value is: %d", i);
return str;
}
In this case it is save to return *str.
No, it isn't.

<snip>

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Nov 19 '07 #7
"Richard Heathfield" <rj*@see.sig.in validschrieb im Newsbeitrag
news:pd******** *************** *******@bt.com. ..
Joachim Schmitz said:
>"arunmib" <ar*****@gmail. comschrieb im Newsbeitrag
<snip>
>>>
int main()
{
char *test(int i);
char *tmp = NULL;
int i = 10;
tmp = test(i);
printf("%s\n", tmp);
free(tmp);
return 0;
}

char *test(int i)
{
char *str = (char*)malloc(2 0);
sprintf(str, "i value is: %d", i);
return str;
}
In this case it is save to return *str.

No, it isn't.
???
Of course I meant 'return str'

Bye, Jojo
Nov 19 '07 #8
In article
<83************ *************** *******@w28g200 0hsf.googlegrou ps.com>,
arunmib <ar*****@gmail. comwrote on Monday 19 Nov 2007 5:19 pm:
On Nov 19, 4:34 pm, santosh <santosh....@gm ail.comwrote:
>In article
<952875bd-9cc5-4cac-8ade-6fa37cdb4...@d2 7g2000prf.googl egroups.com>,
hari <haricib...@gma il.comwrote on Monday 19 Nov 2007 4:57 pm:
Hi all,
Is it legal to return a local variable from function.

Yes. Returning a pointer to it however is dangerous unless the said
local is static.

Well, I have a doubt. If I allocate memory for a local pointer and
return the address of the pointer to the calling function. Now will
this be dangerous. For eg:

int main()
{
char *test(int i);
Generally it's better to place declarations outside functions.
Specifically, it is needed (not strictly speaking, but calling a
function without a prototype is bad coding for most purposes), if a
function other than main() wants to invoke test().
char *tmp = NULL;
int i = 10;
tmp = test(i);
printf("%s\n", tmp);
free(tmp);
return 0;
}

char *test(int i)
{
char *str = (char*)malloc(2 0);
The cast is not recommended practise in C. It can prevent the compiler
from issuing a diagnostic if a prototype for malloc() is not in scope,
as is the case here. That in turn can cause subtle problems, since the
compiler incorrectly assumes that malloc() returns an int, while,
actually, it returns a void *.

Include stdio.h and stdlib.h before the code for this program.
sprintf(str, "i value is: %d", i);
If the value held in 'i' requires more than seven characters to
represent in decimal this sprintf() call will overwrite memory. For
such cases use snprintf().
return str;
This is fine since what is being returned is the _value_ in 'str',
not 'str' itself, which ceases to exist after this return. The value
however is copied and assigned to 'tmp' in main().
}
Nov 19 '07 #9
arunmib wrote:
>
.... snip ...
>
Well, I have a doubt. If I allocate memory for a local pointer and
return the address of the pointer to the calling function. Now will
this be dangerous. For eg:

int main() {
char *test(int i);
char *tmp = NULL;
int i = 10;
tmp = test(i);
printf("%s\n", tmp);
free(tmp);
return 0;
}

char *test(int i) {
char *str = (char*)malloc(2 0);
sprintf(str, "i value is: %d", i);
return str;
}
You didn't return the address of the pointer, you returned the
pointer. All is well (except for the foolish cast on the return
value of malloc, and the lack of #includes, and the missing void in
the main parameter list).

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home .att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Nov 20 '07 #10

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

Similar topics

25
4147
by: cppaddict | last post by:
I'd like to know what goes on under the hood when methods return objects. Eg, I have a simple Point class with two members _x and _y. It's constructor, copy constructor, assignment operator and additon operator (which returns another Point object, and which my question is about) are as follows: Point::Point(int x, int y) : _x(x), _y(y) { }
8
14007
by: Ravindranath Gummadidala | last post by:
Hi All: I am trying to understand the C function call mechanism. Please bear with me as I state what I know: "every invocation of a function causes a frame for that function to be pushed on stack. this contains the arguments this function was called with, address to return to after return from this function (the location in the previous stack frame), location of previous frame on stack (base or start of this frame) and local variables...
23
3612
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;
11
2051
by: Alberto Giménez | last post by:
Hi, I've seen some object oriented programming bits out there and i'm not sure if they're legal. For example: struct Object { int field1; int field2; }; struct SubObject { int field1; /* the same as Object */
17
3057
by: lovecreatesbeauty | last post by:
1. In the following code, is the code (line 11) legal? Is there a notice in the document to tell callers that the parameter s1 should receive an array variable, i.e. type char, but not a variable of char *? p1 and p2 point to the same things but they must be declared as different types? Is it nature? char p1 = "hello123456"; char *p2 = "world"; strncpy(p1, p2, strlen(p2));
2
2095
by: Jess | last post by:
Hello, I understand that if a function "f" has a local variable "a", and after it returns, "a" vanishes. If "f" returns "a" as a result, then I noticed the following: 1. if the return type is "a&", then compiler complains reference to the local variable "a". 2. if the return type is "a", then everything works fine.
14
1947
by: Alexander Stoyakin | last post by:
Hello! Please advise on the following issue. I have a function which returns 1 or 0 in multiple branches, and it must perform the same code before each return, like this: int fun() { if (some code) { restore(param1,param2,param3,param4,param5); return 1;
18
2104
by: terminator(jam) | last post by:
consider: struct memory_pig{//a really large type: memory_pig(){ std::cout<<"mem pig default\n"; //etc... }; memory_pig(memory_pig const&){
10
4011
by: flopbucket | last post by:
Hi, Is this legal? std::string foo() { std::string xyz = "FOO"; return xyz; }
0
9568
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
10007
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
9835
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
8833
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
7379
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
5277
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
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3926
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
2806
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.