Returning pointer to local variable

Discussion in 'C' started by raviinroorkee_7, Nov 7, 2006.

  1. raviinroorkee_7

    raviinroorkee_7 New Member

    Joined:
    Nov 7, 2006
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hi,
    we should avoid returning a pointer to local variable. If one wants to do that then either variable has to be declared static or varable has to be allocated dynamically. In later case calling function should take care of deallocating the variable to avoid memory leaks.
    Can anyone tell me why it works in case of dynamically allocation and static declaration and why not in case of simple local variable?
     
  2. Aztec

    Aztec New Member

    Joined:
    May 9, 2006
    Messages:
    90
    Likes Received:
    0
    Trophy Points:
    0
    As soon as the scope of the function ends i.e after the closing brace } of function, memory allocated(on stack) for all the local variables will be released automatically by compiler. So, returning pointer to some memory which is no longer valid invokes undefined behavior.

    Whereas dynamic memory allocation is on heap/free store and memory allocated from it won't be released by the compiler. If you have allocated something dynamically then you have to deallocate it yourself when memory is no longer required otherwise there will be a memory leak.
    As far as statics are concerned, memory for them is allocated from a special static/global area as soon as the program starts. This memory is released as soon as the programs gets over.

    So, returning pointers on both the latter cases makes sense.
     
    Last edited: Nov 7, 2006

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice