Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use an un-initialized pointer as a function parameter

As I want to pass an uninitialized pointer to a function, it goes runtime error. but if I pass this pointer as a reference, it works OK. I cannot explain why...

class Body
{

};

void check(Body* b)
{
    b = new Body();
}

void checkRef(Body* &b)
{
    b = new Body();
}

int main001()
{
    Body* b;

    //check(b);// error: The variable 'b' is being used without being initialized. (in VS2010)
    checkRef(b); // OK


    return 0;
}

Whats the difference when b is passed to check and checkRef? I get the runtime error in VisualStudio2010. error:The variable 'b' is being used without being initialized.

EDIT: it was a VS2010 debug output. the "error" doesn't appear in release version

like image 688
demaxSH Avatar asked Dec 22 '22 14:12

demaxSH


1 Answers

In order to be equivalent to the checkRef version, your check function should read:

void check(Body** b)
{
    *b = new Body();
}

and called as

check(&b);

If you don't pass the address, as you do in check(b), then you are passing the current value of the pointer b which is indeed uninitialised.

like image 199
Greg Hewgill Avatar answered Dec 24 '22 03:12

Greg Hewgill