Yibo Yang
Yibo Yang

Reputation: 2413

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?

Upvotes: 0

Views: 10845

Answers (3)

Bretzelus
Bretzelus

Reputation: 345

C4700 is not an error. DOT. But MSVC fails to compile on C4700 which is an error because the "/sdl" compiler switch is on by default C4700 discution on visualstudio site , MSDN /sdl switch for vs 2012+

Upvotes: 1

jrsala
jrsala

Reputation: 1967

Instead of

int *num; // num points to somewhere random
*num = 25; // writing somewhere random makes zero sense
           // and if your OS allowed you to do it, you would
           // crash your computer very often.

you must write

int num = 25;
int *pnum = &num; // pnum is a pointer to int which has been
                  // initialized with the address of num

And the same thing applies the struct's content.

Upvotes: 4

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

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.

Upvotes: 3

Related Questions