In Visual Studio, it seems like pointer to member variables are 32 bit signed integers behind the scenes (even in 64 bit mode), and a null-pointer is -1 in that context. So if I have a class like:
#include <iostream> #include <cstdint> struct Foo { char arr1[INT_MAX]; char arr2[INT_MAX]; char ch1; char ch2; }; int main() { auto p = &Foo::ch2; std::cout << (p?"Not null":"null") << '\n'; }
It compiles, and prints "null". So, am I causing some kind of undefined behavior, or was the compiler supposed to reject this code and this is a bug in the compiler?
Edit:
It appears that I can keep the "2 INT_MAX
arrays plus 2 chars" pattern and only in that case the compiler allows me to add as many members as I wish and the second character is always considered to be null. See demo. If I changed the pattern slightly (like 1 or 3 chars instead of 2 at some point) it complains that the class is too large.
Use Pointer Value as Condition to Check if Pointer Is NULL in C++ Null pointers are evaluated as false when they are used in logical expressions. Thus, we can put a given pointer in the if statement condition to check if it's null.
The only way a this pointer can be NULL is if some code in the program has exhibited undefined behaviour. void *place = nullptr; MyClass *object = new (place) MyClass();
Examples of Null Pointerchar *ptr=(char *)0; double *ptr=(double *)0; char *ptr='\0';
Because a null pointer does not point to a meaningful object, an attempt to dereference (i.e., access the data stored at that memory location) a null pointer usually (but not always) causes a run-time error or immediate program crash.
The size limit of an object is implementation defined, per Annex B of the standard [1]. Your struct is of an absurd size.
If the struct is:
struct Foo { char arr1[INT_MAX]; //char arr2[INT_MAX]; char ch1; char ch2; };
... the size of your struct in a relatively recent version of 64-bit MSVC appears to be around 2147483649 bytes. If you then add in arr2, suddenly sizeof will tell you that Foo is of size 1.
The C++ standard (Annex B) states that the compiler must document limitations, which MSVC does [2]. It states that it follows the recommended limit. Annex B, Section 2.17 provides a recommended limit of 262144(?) for the size of an object. While it's clear that MSVC can handle more than that, it documents that it follows that minimum recommendation so I'd assume you should take care when your object size is more than that.
[1] http://eel.is/c++draft/implimits
[2] https://docs.microsoft.com/en-us/cpp/cpp/compiler-limits?view=vs-2019
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With