PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 28, 2022

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

 April 28, 2022     c++, pointers, struct, visual-studio, warnings     No comments   

Issue

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?


Solution

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.



Answered By - Benjamin Lindley
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing