Thread: Returning a pointer

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    52

    Question Returning a pointer

    Hi,

    I have a real beginner question for you all.

    Code:
    double * GetSalary()
    {
        double salary = 26.48;
        double *HourlySalary = &salary;
    
        return HourlySalary;
    }
    I found the example above on a website. I thought that a double declared in a function is allocated space on the run-time stack and is destroyed after the function returns. So if you then have

    Code:
    main()
    {
        double * ptr = GetSalary();
    }
    aren't you then going to have ptr pointing to an address in memory that will be holding different data?

    Also, when GetSalary() returns, does the pointer HourlySalary get destroyed just like any other primitive upon return?

    Thanks
    Last edited by Canadian0469; 11-16-2008 at 04:06 AM.

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Correct. Either the website gives bad examples, or it was meant as a counter-example.

    To be precise, the pointer will point to a location that is simply invalid. It's undefined what data it holds. (Until you call another function, it will probably still hold the old value, which makes this even more dangerous: it often appears to work.)
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 01:34 PM
  3. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  4. Another Linked List plee
    By Dragoncaster131 in forum C Programming
    Replies: 3
    Last Post: 05-15-2004, 05:40 PM
  5. returning pointer to string between exe and dll
    By evilpope in forum C Programming
    Replies: 2
    Last Post: 05-15-2003, 12:16 PM