Thread: returning pointers from a function

  1. #1
    Registered User
    Join Date
    Jul 2003
    Posts
    450

    returning pointers from a function

    If I use dynamic allocation to create node in a binary tree within a function, will these pointers exisist outside of the function.

    I was warned not to return pointers to temporary variables from a function so it seems there are three options. Pass the pointer as an argument to the function and return it after manipulation, use a global pointer (bad idea I understand), or I think use dynamic memory allocation and delete the pointers in another function.

    Are these all of the options for returning of type pointer or pointer to functions?

    Not dealing with classes yet just a simple struct, and functions.

  2. #2
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Returning a pointer to something that was created on the stack is a bad idea as it will be destroyed when it goes out of scope, so your pointer will point to either nothing in particular, or something owned by another part of your program (which leads to unpredictable and undefined behavior), unless the variable was static (which probably isn't what you want). Here is an example of what not to do:
    Code:
    int* foo( )
    {
      int x = 3;
      return &x; // Once the function returns, x goes out of scope, so what your pointer points to is unpredictable.
    }
    You can, however, return a pointer to something that was created on the heap without fear of it going out of scope. You must, however, make sure that the memory allocated is later freed.
    Code:
    int* foo( )
    {
      int* p = new int;
      *p = 3;
      return p;
    }
    
    void bar( )
    {
      int* r = foo( );
      // ...
      delete r;
    
      // The following, however, is a memory leak.
      foo( ); // Now, nothing points to the allocated memory, so it cannot be freed.
    }
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  3. #3
    Registered User
    Join Date
    Jul 2003
    Posts
    450
    Thanks that helps clarify what I was thinking!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Variable pointers and function pointers
    By Luciferek in forum C++ Programming
    Replies: 11
    Last Post: 08-02-2008, 02:04 AM
  2. doubt in c parser coding
    By akshara.sinha in forum C Programming
    Replies: 4
    Last Post: 12-23-2007, 01:49 PM
  3. Returning an Array of Pointers to Objects
    By randomalias in forum C++ Programming
    Replies: 4
    Last Post: 04-29-2006, 02:45 PM
  4. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM
  5. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM