1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Pointer's in C

Discussion in 'C' started by creative, May 22, 2010.

  1. creative

    creative New Member

    Joined:
    Feb 15, 2010
    Messages:
    87
    Likes Received:
    0
    Trophy Points:
    0
    I write a small program.
    My teacher tells me that this program not work since the return value
    from function foo() is not guaranteed to be preserved. I think this is
    correct usage of pointers.

    I dont think so. I think my teacher wrong.

    Please explain.
     
  2. techme

    techme New Member

    Joined:
    Feb 15, 2010
    Messages:
    86
    Likes Received:
    0
    Trophy Points:
    0
    My teacher tells me that this program not work since the return value
    from function foo() is not guaranteed to be preserved. I think this is
    correct usage of pointers.

    I dont think so. I think my teacher wrong.

    Your teacher is(!) right. You're returning the address of an auto
    ("local") array from foo(). This array, like all auto objects, has
    automatic duration, which means that once you return from foo(), it goes
    out of existence, and any attempt to use it invokes undefined behaviour,
    which means it may do anything from appearing to work correctly to crash
    hard. Sure, it may _look_ like it still exists after the return, in this
    simple test program. However, you cannot rely on this at all. In any
    more realistic program you're likely to read garbage.
     
  3. techinspiration

    techinspiration New Member

    Joined:
    Feb 14, 2010
    Messages:
    54
    Likes Received:
    0
    Trophy Points:
    0
    I write a small program.
    Code:
    #include <string.h>
    
     char *foo(void);
     char *a = "I like C";
    
     int main(void) {
     if((strcmp(a,foo())) {
     printf("\n i like c");
    
    You should in general terminate an output line with a newline in
    order to guarantee that it appears.
    
     }
     }
    
     char *foo(void)
     {
     char b[100] = "I like C";
     return b;
     }
    
    My teacher tells me that this program not work since the return value
    from function foo() is not guaranteed to be preserved. I think this is
    correct usage of pointers.

    I dont think so. I think my teacher wrong.

    Your teacher is correct. The array b is not guaranteed to
    continue to exist after foo() returns. It might, for instance,
    be in a location that is not accessible after the function
    returns, or it might get overwritten. Make it static and it will
    work.
     

Share This Page