开发者

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


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.


Body* b does not set b to point to anything sensible. So it may point to some random location which could cause the earth to shift a bit.

Passing it to check(by value for the pointer) does not make it initialised in any way

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

If you passed it by pointer to pointer, it should be okay

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

And the call

check(&b);

Better done in C++ way with the reference example you give since that updates the referenced pointer value to point to the newly allocated Body


In Body * &b b is an alias of/reference to the b in main - so when you assign to it you modify the b in main. In Body* b b is a local copy of the b in main, you're modifying this local copy and not the b in main.

Your runtime error is likely due to using the uninitialized b in main.

EDIT: The actual error you get is an extra check-for-typical-problems mechanism embedded into your code by your compiler. It detects that you pass something uninitialized by value, which doesn't make sense, and therefore generates this error.

If you disable this behavior, the application will appear to function properly until you try to dereference the uninitialized b in main


I don't know why you're seeing a run-time error; at most I would expect to receive a compile-time warning/error. But you can probably fix it by initialising b to NULL (but this won't fix your program; see below...)

The difference between the first and the second function call is that the first one will cause a memory-leak. You are passing the pointer by-value, so inside check() you are working with a copy of that pointer. You assign this copy, but this doesn't affect the value of the pointer in main(), so when you leave the function, there is no way to access the memory that was obtained by new.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜