CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Is this safe?

  1. #1
    Join Date
    Aug 2006
    Posts
    157

    Is this safe?

    The following code fails as expected because I am passing an invalid pointer:
    Code:
    void func2(char* c, char* d) {
       c = d;  
    }
    
    void func() {
       char* c = NULL;
       char* d = new char('f');
       func2(c, d);
       char e = *c;
       printf(e);
    }
    
    int main(int argc, const char* argv[])
    {
    	func();
    }
    But if I change func2 to...
    Code:
    void func2(char*& c, char* d) {
       c = d;  
    }
    ... it works because I'm passing a reference to the pointer.

    I don't really understand the mechanic that allows this to work. Since the pointer is invalid why does passing it as a reference make a difference?
    Cheers.

  2. #2
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: Is this safe?

    Check with your debugger what the value of 'c' is before and after the call to func2.
    A pointer is just like any other value. In the first case you are passing the pointer by value, in the second by reference. Hence, in the first case the value at the call site is not changed and in the second it is.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  3. #3
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Is this safe?

    You may be under the impression that func2 is copying the value 'f' from one location to another. It isn't. It's merely assigning a second pointer to point at the same location as the first one. Hence, after the (second version of the) call to func2, c is no longer an invalid pointer: it's pointing at the same thing as d.

    You do still have a bug, though, in that the new'd memory is never released.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured