Uninitialized pointers in code

int* ptr = NULL; //Is this going to avoid the problem This will cause ptr to point to NULL which you can explicitly check for as a default/uninitialized value. It prevents the problem you describe, but a careless programmer can still accidentally dereference a null pointer without checking, causing undefined behaviour. The main advantage is … Read more

Is dereferencing null pointer valid in sizeof operation [duplicate]

Why does this work? This works because sizeof is a compile time construct, with the exception of variable length arrays is not evaluated at all. If we look at the C99 draft standard section 6.5.3.4 The sizeof operator paragraph 2 says(emphasis mine): […] The size is determined from the type of the operand. The result … Read more

What is the overhead of Rust’s Option type?

Yes, there is some compiler magic that optimises Option<ptr> to a single pointer (most of the time). use std::mem::size_of; macro_rules! show_size { (header) => ( println!(“{:<22} {:>4} {}”, “Type”, “T”, “Option<T>”); ); ($t:ty) => ( println!(“{:<22} {:4} {:4}”, stringify!($t), size_of::<$t>(), size_of::<Option<$t>>()) ) } fn main() { show_size!(header); show_size!(i32); show_size!(&i32); show_size!(Box<i32>); show_size!(&[i32]); show_size!(Vec<i32>); show_size!(Result<(), Box<i32>>); } … Read more

Can I use if (pointer) instead of if (pointer != NULL)?

You can; the null pointer is implicitly converted into boolean false while non-null pointers are converted into true. From the C++11 standard, section on Boolean Conversions: A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null … Read more

Is it safe to delete a NULL pointer?

delete performs the check anyway, so checking it on your side adds overhead and looks uglier. A very good practice is setting the pointer to NULL after delete (helps avoiding double deletion and other similar memory corruption problems). I’d also love if delete by default was setting the parameter to NULL like in #define my_delete(x) … Read more

When does invoking a member function on a null instance result in undefined behavior?

Both (a) and (b) result in undefined behavior. It’s always undefined behavior to call a member function through a null pointer. If the function is static, it’s technically undefined as well, but there’s some dispute. The first thing to understand is why it’s undefined behavior to dereference a null pointer. In C++03, there’s actually a … Read more