Yibo Yang Yibo Yang - 27 days ago 7
C++ Question

How to fix C4700 warning in C++ with uninitialized pointers?

I have read through many of the previous posts on C4700, but I can't seem to find a solution to my problem.

I have a little script written to demonstrate struct pointers:

struct foo
{
int * bar;
};

#include<iostream>
using namespace std;
int main()
{
foo * fooptr;
int * num;
*num = 25;
*fooptr->bar = *num;
cout << "now fooptr points to a foo struct whose bar points to: " << *fooptr->bar;

fooptr->bar = num;
cout <<"now fooptr's struct's bar shares memory address with num at " <<num;

return 0;
}


When I compile it, I get two C4700 warnings for uninitialized local variables num and fooptr used.
I went ahead and initialized both to NULL, so the compiler error went away but not surprisingly I got an exception:

Unhandled exception at 0x00265DF7 in testing.exe: 0xC0000005: Access violation writing location 0x00000000.

You see I always thought that when I don't initialize those pointers, they'll be automatically initialized with random addresses (just like uninitialized ints/chars/doubles will be assigned garbages)--so shouldn't that be the case here?

If initialization in this case is indeed absolutely necessary (why?), then is there an easy workaround for this problem?

Answer Source

Uninitialized variables are not initialized to random values, they are uninitialized. On a machine code level, they have whatever value was there when they were created. This may or may not be the address of an actual object. Either way, it is undefined behavior to try to access an uninitialized pointer value as if there is an object at that address.

So, your compiler is doing you a favor by issuing a warning (it is not required to do so), because your code has undefined behavior.

then is there an easy workaround for this problem?

Set your pointers to point to valid objects before dereferencing them. If you don't, then there are no promises about what behavior your program will have.