Returning "stack" variables from a function

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Generic Usenet Account

    #1

    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

  • Alex Fraser

    #2
    Re: Returning "stack&quo t; variables from a function

    "Generic Usenet Account" <usenet@sta.sam sung.com> wrote in message
    news:1114589838 .584497.242120@ g14g2000cwa.goo glegroups.com.. .
    [snip][color=blue]
    > 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).[/color]

    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


    Comment

    • Kevin Bracey

      #3
      Re: Returning &quot;stack&quo t; variables from a function

      In message <1114589838.584 497.242120@g14g 2000cwa.googleg roups.com>
      "Generic Usenet Account" <usenet@sta.sam sung.com> wrote:
      [color=blue]
      > 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).[/color]

      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/

      Comment

      • Ravi Uday

        #4
        Re: Returning &quot;stack&quo t; variables from a function



        Generic Usenet Account wrote:
        [color=blue]
        > 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.
        >[/color]
        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
        [color=blue]
        > 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
        >[/color]

        Comment

        • Lawrence Kirby

          #5
          Re: Returning &quot;stack&quo t; variables from a function

          On Wed, 27 Apr 2005 01:17:18 -0700, Generic Usenet Account wrote:
          [color=blue]
          > 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?[/color]

          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.
          [color=blue]
          > 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.[/color]

          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.
          [color=blue]
          > 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).[/color]

          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

          Comment

          • MJ

            #6
            Re: Returning &quot;stack&quo t; variables from a function

            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

            Comment

            • Dr A. N. Walker

              #7
              Re: Returning &quot;stack&quo t; variables from a function

              In article <1114589838.584 497.242120@g14g 2000cwa.googleg roups.com>,
              Generic Usenet Account <usenet@sta.sam sung.com> wrote:[color=blue]
              >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?[/color]

              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.
              [color=blue]
              >In all fairness to my colleague, he does admit that it is inefficient
              >to return datastructures from functions, [...].[/color]

              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.
              anw@maths.nott. ac.uk

              Comment

              Working...