Search code examples
c++pointerswarningsdynamic-memory-allocationnew-operator

Warning in C++: Pointer holds a value that must be examined when trying to assign new int32_t


I was trying to learn dynamic memory allocation in C++. My program compiles and works, but Visual Studio throws these warnings at me.

What do they mean?

Warning C28193  'ptr' holds a value that must be examined.
Warning C28182  Dereferencing NULL pointer. 'ptr' contains the same NULL value as 
'new(1*4, nothrow)'

My code:

#include <iostream>
#include <cstdint>

int main()
{
    int* ptr = nullptr;

    if (!ptr) {
        ptr = new (std::nothrow) int32_t;
        *ptr = 10;
    }

    std::cout << *ptr << "\n";

}

Solution

  • new (std::nothrow) int32_t
    

    Attempts to allocate the memory for int32_t, and if it cannot, it doesn't throw an exception, it returns nullptr.

    You go ahead and assign a number (10) to it, but you need to first determine if the memory allocation succeeded by checking if ptr is nullptr or not before assigning the value. It's trying to tell you that you need some error checking.

    Same thing when you print it out, it may be a nullptr and you need to examine that.