2

I'm getting an error potentially uninitialized local pointer variable 'y' used & potentially uninitialized local pointer variable 'z' used, in the code provided below. Please help me with the solution?

UINT8* x = new UINT8[512];
if (!x) goto clean;

//UINT32* y = NULL;
UINT32* y = new UINT32[4];
if (!y) goto clean;

//char* z = NULL;
char* z = new char[512];
if (!z) goto clean;

{.... Some Code....}

clean:

    if (x) delete[] x;
    if (y) delete[] y;
    if (z) delete[] z;
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
user9059547
  • 67
  • 1
  • 12

3 Answers3

6

Move all the initializations to the beginning. Otherwise with if (!x) goto clean; and jumps to clean, y and z are still not initialized.

UINT8* x = NULL;
UINT32* y = NULL;
char* z = NULL;

x = new UINT8[512];
if (!x) goto clean;

y = new UINT32[4];
if (!y) goto clean;

z = new char[512];
if (!z) goto clean;

PS: As others pointed, in modern C++, raw pointers (and new and delete), and goto should not be used in general. You might want to refer to The Definitive C++ Book Guide and List.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
3

For reference, here's the 21st century version:

std::vector<std::uint8_t> x {512};
std::vector<std::uint32_t> y {4};
std::vector<char> z {512}; // Or std::string

Notice the lack of clean:. This is intentional. The compiler inserts clean-up code.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • And `std::array` for 2011 version. – songyuanyao Feb 05 '18 at 10:03
  • 2
    @songyuanyao: I'm converting like for like. Presumably the old code had good reason to put these containers on the heap, so I kept that. The whole point of RAII is that you can get the semantics of local variables even with heap allocation. – MSalters Feb 05 '18 at 10:12
2

If you jump to goto from here:

if (!x) goto clean;

Then y and z would have never been initialized here:

if (x) delete[] x;
if (y) delete[] y;
if (z) delete[] z;

The real answer to this question is: do not use goto, especially in C++. Use std::unique_ptr instead to manage your memory automatically.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416