null-pointer

What is the overhead of Rust's Option type?

一笑奈何 提交于 2019-11-26 07:37:47
问题 In Rust, references can never be null, so in case where you actually need null, such as a linked list, you use the Option type: struct Element { value: i32, next: Option<Box<Element>>, } How much overhead is involved in this in terms of memory allocation and steps to dereference compared to a simple pointer? Is there some \"magic\" in the compiler/runtime to make Option cost-free, or less costly than if one were to implement Option by oneself in a non-core library using the same enum

Is dereferencing null pointer valid in sizeof operation [duplicate]

眉间皱痕 提交于 2019-11-26 06:48:10
问题 This question already has an answer here: Why doesn't my program seg fault when I dereference a NULL pointer inside of malloc? 4 answers I\'ve come across a snippet of code that to me should crash with a segmentation fault , and yet it works without a hitch. The code in question plus relevant data structure is as follows (with associated comment found right above): typedef struct { double length; unsigned char nPlaced; unsigned char path[0]; } RouteDefinition* Alloc_RouteDefinition() { // NB:

Accessing class members on a NULL pointer

倖福魔咒の 提交于 2019-11-26 01:29:11
问题 I was experimenting with C++ and found the below code as very strange. class Foo{ public: virtual void say_virtual_hi(){ std::cout << \"Virtual Hi\"; } void say_hi() { std::cout << \"Hi\"; } }; int main(int argc, char** argv) { Foo* foo = 0; foo->say_hi(); // works well foo->say_virtual_hi(); // will crash the app return 0; } I know that the virtual method call crashes because it requires a vtable lookup and can only work with valid objects. I have the following questions How does the non

Is it safe to delete a NULL pointer?

耗尽温柔 提交于 2019-11-25 23:15:56
问题 Is it safe to delete a NULL pointer? And is it a good coding style? 回答1: 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) {delete x; x = NULL;} (I know about R and L values, but wouldn't it be nice?) 回答2: From

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

血红的双手。 提交于 2019-11-25 21:42:04
问题 Consider the following code: #include <iostream> struct foo { // (a): void bar() { std::cout << \"gman was here\" << std::endl; } // (b): void baz() { x = 5; } int x; }; int main() { foo* f = 0; f->bar(); // (a) f->baz(); // (b) } We expect (b) to crash, because there is no corresponding member x for the null pointer. In practice, (a) doesn\'t crash because the this pointer is never used. Because (b) dereferences the this pointer ( (*this).x = 5; ), and this is null, the program enters