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

Returning "stack" variables from a function

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 seem to think
so. According to my colleague, if the data structure does not "deep
copy" issues, it is perfectly okay to return a local variable. This is
because at the point of invocation, a copy of the data structure is
made.

In all fairness to my colleague, he does admit that it is inefficient
to return datastructures from functions, but he passionately belives in
the legitimacy of returning stack data structures without "deep copy"
issues (i.e. without any pointer fields).
Thanks,
Keerti

Nov 14 '05 #1
6 2398
"Generic Usenet Account" <us****@sta.samsung.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
[snip]
In all fairness to my colleague, he does admit that it is inefficient
to return datastructures from functions, but he passionately belives in
the legitimacy of returning stack data structures without "deep copy"
issues (i.e. without any pointer fields).


Your colleague is correct, except that it is not necessarily inefficient. It
may actually be faster than having a pointer to store the result as a
parameter.

Also, although you haven't suggested your colleague thinks otherwise, it is
not always a problem to return a struct that /does/ contain pointers. For
example, a struct containing a pointer to a string literal or memory
allocated by malloc().

The second point is essentially the same restriction as applies to a
function returning (just) a pointer: there is no inherent problem if the
pointer is still valid after the function ends. This means, for example, the
following is "legal" (in principle):

struct obj {
/* ... members, including pointers ... */
};

struct obj func(struct obj orig) {
struct obj copy;
/* ... code to make copy a "deep copy" of orig ... */
return copy;
}

Alex
Nov 14 '05 #2
In message <11**********************@g14g2000cwa.googlegroups .com>
"Generic Usenet Account" <us****@sta.samsung.com> wrote:
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 seem to think
so. According to my colleague, if the data structure does not "deep
copy" issues, it is perfectly okay to return a local variable. This is
because at the point of invocation, a copy of the data structure is
made.

In all fairness to my colleague, he does admit that it is inefficient
to return datastructures from functions, but he passionately belives in
the legitimacy of returning stack data structures without "deep copy"
issues (i.e. without any pointer fields).


There's no legitimacy problem - returning (or indeed passing) a structure is
just as legal in C as returning or passing a scalar type.

There may be an efficiency problem - depending on your implementation,
a data copy may be involved in transferring the structure out.

For example, given:

struct blah foo(void)
{
struct blah result;
result.a = 1;
result.b = 2;
result.c = 3;
return result;
}

{
struct blah x;
x = foo();
}

a typical standard C implementation would generate code as if you had
written:

void foo(struct blah *r)
{
struct blah result; // local structure on stack
result.a = 1;
result.b = 2;
result.c = 3;

*r = result; // data copy
}

{
struct blah x;
foo(&x);
}

Writing your code to fill in a passed pointer instead would be more
efficient. However, there's nothing stopping an intelligent compiler from
compiling it like this automatically:

void foo(struct blah *r)
{
r->a = 1;
r->b = 2;
r->c = 3;
}

{
struct blah x;
foo(&x);
}

So in fact that may not be any real efficiency problem at all. For this
optimisation to work, the compiler would have to spot that "return result"
was the exit path in all cases, and that result never had its address taken.

--
Kevin Bracey, Principal Software Engineer
Tematic Ltd Tel: +44 (0) 1223 503464
182-190 Newmarket Road Fax: +44 (0) 1728 727430
Cambridge, CB5 8HE, United Kingdom WWW: http://www.tematic.com/
Nov 14 '05 #3


Generic Usenet Account wrote:
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 seem to think
so. According to my colleague, if the data structure does not "deep
copy" issues, it is perfectly okay to return a local variable. This is
because at the point of invocation, a copy of the data structure is
made.
I feel its perfectly ok to return a pointer to data structures defined
inside a function. Its far better than returning each field (deep copy -
if that is what you meant)

<UNTESTED>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct a{
int i;
char *j;
}A;

A *fn (void)
{
A *data = malloc(sizeof A);
data->i = 10;
data->j = malloc (sizeof data->j);
strcpy (j, "Hello");
return data; /* returning local datastruc from this fn !*/
}

int main ()
{

A *use;

use = fn();

/*
Makeuse of this structure and be sure to free it once in the end
before you exit out of main
*/

return 0;
}

- Ravi
In all fairness to my colleague, he does admit that it is inefficient
to return datastructures from functions, but he passionately belives in
the legitimacy of returning stack data structures without "deep copy"
issues (i.e. without any pointer fields).
Thanks,
Keerti


Nov 14 '05 #4
On Wed, 27 Apr 2005 01:17:18 -0700, Generic Usenet Account wrote:
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?
Yes, that's fine. Returning any value in effect creates a copy of it so it
doesn't matter if the original disappears. What you must not do is return
a *pointer* to a function's local automatic variable. It is also OK for
the structure to contain pointer fields as long as the caller doesn't use
any such pointers that point to an automatic variable. The rule is simple:
you can't use the value of a pointer if the thing it points at no longer
exists.
I
think it is a bad idea, but one of my colleagues does not seem to think
so. According to my colleague, if the data structure does not "deep
copy" issues, it is perfectly okay to return a local variable. This is
because at the point of invocation, a copy of the data structure is
made.
Yes. "Deep copy" may or may not be an issue, pointers in the struct may be
set appropriately anyway, e.g. to malloc'd memory.
In all fairness to my colleague, he does admit that it is inefficient to
return datastructures from functions, but he passionately belives in the
legitimacy of returning stack data structures without "deep copy" issues
(i.e. without any pointer fields).


It may not be inefficient if the structure is small, e.g. an x,y point
structure. There are even examples in the standard library e.g. the div()
function.

Lawrence

Nov 14 '05 #5
MJ
Its fine to return a local structure. If there is no pointer in the
strucutre and no dynamic allocation, its fine. But the problem comes
when you want to expand your structure. So keeping design aspect in
mind you should never do such thing. Its will put limitation for
further expansion of the structure...

Regards,
MJ

Nov 14 '05 #6
In article <11**********************@g14g2000cwa.googlegroups .com>,
Generic Usenet Account <us****@sta.samsung.com> wrote:
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?
You seem to be asking about C, but you posted also to more
general groups. In general, and C is no exception, you are in deep
doodah if you have pointers to objects that no longer exist, and
apart from that you are usually perfectly OK with anything that the
language lets you do [compiler bugs/features excepted]. Function
returns are a special case in that it is normal to have objects
local to the procedure and to want to access "the result" elsewhere
in the program, but the underlying rule is no different. You get
into exactly the same trouble of "dangling pointers" in C if you
assign a more-local variable to a less-local pointer and then leave
the more-local scope and still expect to use the pointer, whether
or not the more/less is actually inside/outside a procedure.

There are some language-dependent "features" in this sort
of area. For example, in Algol it is forbidden to assign *any*
object to a pointer of wider scope or to return *any* result into
an environ of wider scope. So whatever you do will [or should!]
either work properly or else fail at the moment you commit the sin,
not much later when you try to use the pointer/result and *then*
discover [or not] that you are overwriting some other object. This
makes debugging very much easier. Other languages are more-or-less
relaxed about this.
In all fairness to my colleague, he does admit that it is inefficient
to return datastructures from functions, [...].


If it is inefficient, that is a feature of a particular
implementation and a particular problem. My strong advice on all
such occasions is to write code correctly and naturally in the
first instance, and to worry about efficiency only if it turns
out to matter.

--
Andy Walker, School of MathSci., Univ. of Nott'm, UK.
an*@maths.nott.ac.uk
Nov 14 '05 #7

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...
81
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there...
4
by: anonymous | last post by:
Thanks your reply. The article I read is from www.hakin9.org/en/attachments/stackoverflow_en.pdf. And you're right. I don't know it very clearly. And that's why I want to understand it; for it's...
15
by: Joe Van Dyk | last post by:
Can someone explain what a heap and what a stack is? And why I should care? I used to know, but then I forgot. And I can't seem to find it in the C++ FAQ. I keep reading how allocating from...
21
by: Steven T. Hatton | last post by:
I'm trying to improve my formal understanding of C++. One significant part of that effort involves clarifying my understanding of the vocabulary used to describe the language. This is from the...
13
by: deepak | last post by:
Hi In the following function how the memory 'll be allocated. 1) Will it allocate memory for all the char's together or allocate for first char. then for int then for float and after this only...
94
by: Samuel R. Neff | last post by:
When is it appropriate to use "volatile" keyword? The docs simply state: " The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock...
3
Walt in Decatur
by: Walt in Decatur | last post by:
I have set up a bunch of subforms to appear in the same spot on the screen relative to the main form. I have set up command buttons with open and close each subform. However, if I have several open...
0
by: raylopez99 | last post by:
I ran afoul of this Compiler error CS1612 recently, when trying to modify a Point, which I had made have a property. It's pointless to do this (initially it will compile, but you'll run into...
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
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
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,...
0
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...
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
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

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.