|
-
March 3rd, 2011, 05:04 PM
#1
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.
-
March 3rd, 2011, 05:21 PM
#2
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
-
March 3rd, 2011, 05:39 PM
#3
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|