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

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 13125
In article <95**********************************@d27g2000prf. googlegroups.com>,
hari <ha********@gmail.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

--
"Consideration 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**********************************@d27g2000prf. googlegroups.com>,
hari <ha********@gmail.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....@gmail.comwrote:
In article
<952875bd-9cc5-4cac-8ade-6fa37cdb4...@d27g2000prf.googlegroups.com>,
hari <haricib...@gmail.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(20);
sprintf(str, "i value is: %d", i);
return str;
}
Nov 19 '07 #4
"arunmib" <ar*****@gmail.comschrieb im Newsbeitrag
news:83**********************************@w28g2000 hsf.googlegroups.com...
On Nov 19, 4:34 pm, santosh <santosh....@gmail.comwrote:
>In article
<952875bd-9cc5-4cac-8ade-6fa37cdb4...@d27g2000prf.googlegroups.com>,
hari <haricib...@gmail.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(20);
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(20);
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(20);
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.invalidschrieb 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(20);
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**********************************@w28g2000hsf. googlegroups.com>,
arunmib <ar*****@gmail.comwrote on Monday 19 Nov 2007 5:19 pm:
On Nov 19, 4:34 pm, santosh <santosh....@gmail.comwrote:
>In article
<952875bd-9cc5-4cac-8ade-6fa37cdb4...@d27g2000prf.googlegroups.com>,
hari <haricib...@gmail.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(20);
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(20);
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
Thanks for all your replies.

The code I gave was only to make the understanding of my question's
concept and thats it, nothing more nothing less. No intention for
compiling or doing any other thing with the code. yeah, i know you
need to do #includes and about casting of 'malloc' return, use
snprintf instead of sprintf etc..
Nov 20 '07 #11
arunmib said:
Thanks for all your replies.

The code I gave was only to make the understanding of my question's
concept and thats it, nothing more nothing less. No intention for
compiling or doing any other thing with the code. yeah, i know you
need to do #includes and about casting of 'malloc' return,
About *NOT* casting of malloc return value. There is no benefit to casting
it, and a slight cost in doing so.
use snprintf instead of sprintf etc..
Why? If I tried that, my compiler would laugh at me, and my linker would
have hysterics.

--
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 20 '07 #12
In article
<2f**********************************@c29g2000hsa. googlegroups.com>,
arunmib <ar*****@gmail.comwrote on Tuesday 20 Nov 2007 10:28 am:
Thanks for all your replies.

The code I gave was only to make the understanding of my question's
concept and thats it, nothing more nothing less. No intention for
compiling or doing any other thing with the code.
Personally I always compile code, even trivial, illustrative programs. A
good compiler, (with the appropriate switches), and a lint program can
turn up a surprising amount of issues with even small amounts of code.

Nov 20 '07 #13
On Mon, 19 Nov 2007 12:55:45 +0100, "Joachim Schmitz"
<no*********@schmitz-digital.dewrote:
"arunmib" <ar*****@gmail.comschrieb im Newsbeitrag
news:83**********************************@w28g2000 hsf.googlegroups.com...
char *test(int i)
{
char *str = (char*)malloc(20);
sprintf(str, "i value is: %d", i);
return str;
}
In this case it is save to return *str.
Corrected to (the value of) str. Yes.
It is unsafe though to a) cast the result of the malloc,
Not strictly unsafe, but unhelpful because it can mask the error of
not #include'ing the required header, and at best is clutter.
b) not check whether it succeededs and then writing to
/ read from the unchecked result,
Yes.
c) pass an int to that function that
requires more than 7 characters in decimal
7? How's that? More than 19, yes, or negative more than 18. That would
require int >= 61 bits, which is permitted by the Standard but rare.
Although there is one person here who would make it more common. <G>

- formerly david.thompson1 || achar(64) || worldnet.att.net
Dec 2 '07 #14

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

Similar topics

25
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...
8
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...
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;
11
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; /*...
17
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...
2
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...
14
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...
18
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
by: flopbucket | last post by:
Hi, Is this legal? std::string foo() { std::string xyz = "FOO"; return xyz; }
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.