Example of error caused by UB of incrementing a NULL pointer

后端 未结 4 1782
滥情空心
滥情空心 2020-12-10 07:05

This code :

int *p = nullptr;
p++;

cause undefined behaviour as it was discussed in Is incrementing a null pointer well-defined?

Bu

4条回答
  •  醉酒成梦
    2020-12-10 07:53

    This is just for completion, but the link proposed by @HansPassant in comment really deserves to be cited as an answer.

    All references are here, following is just some extracts

    This article is about a new memory-safe interpretation of the C abstract machine that provides stronger protection to benefit security and debugging ... [Writers] demonstrate that it is possible for a memory-safe implementation of C to support not just the C abstract machine as specified, but a broader interpretation that is still compatible with existing code. By enforcing the model in hardware, our implementation provides memory safety that can be used to provide high-level security properties for C ...

    [Implementation] memory capabilities are represented as the triplet (base, bound, permissions), which is loosely packed into a 256-bit value. Here base provides an offset into a virtual address region, and bound limits the size of the region accessed ... Special capability load and store instructions allow capabilities to be spilled to the stack or stored in data structures, just like pointers ... with the caveat that pointer subtraction is not allowed.

    The addition of permissions allows capabilities to be tokens granting certain rights to the referenced memory. For example, a memory capability may have permissions to read data and capabilities, but not to write them (or just to write data but not capabilities). Attempting any of the operations that is not permitted will cause a trap.

    [The] results confirm that it is possible to retain the strong semantics of a capability-system memory model (which provides non-bypassable memory protection) without sacrificing the advantages of a low-level language.

    (emphasize mine)

    That means that even if it is not an operational compiler, researches exists to build one that could trap on incorrect pointer usages, and have already been published.

提交回复
热议问题