Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading