Skip to content

[Coding Guideline]: Do not invoke undefined behavior #190

@AchimKriso

Description

@AchimKriso

Chapter

Unsafety

Guideline Title

Undefined behavior shall not occur during the execution of a program

Category

Required

Status

Draft

Release Begin

1.0.0

Release End

latest

FLS Paragraph ID

fls_ovn9czwnwxue

Decidability

Undecidable

Scope

System

Tags

undefined-behavior, defect

Amplification

This rule addresses all instances of undefined behavior not already covered by other guidelines.

Exception(s)

No response

Rationale

Once an execution encounters undefined behavior it is impossible to reason about it anymore.
Instances of undefined behavior can manifest in any kind of undesired behavior like crashes or silent memory corruption.

Non-Compliant Example - Prose

First Example:
The only allowed representation of bool is either 0 or 1.
Therefore, transmuting 3_u8 to bool violates its validity invariant and is undefined behavior.

Second Example:
A necessary condition to read the value behind a pointer is that it points to a valid allocation.
This is never the case for a null pointer, therefore reading it is undefined behavior.
See the safety precondition of :std:std::ptr::read.

Non-Compliant Example - Code

fn example_function() -> bool {
    unsafe {
        std::transmute<bool>(3_u8)
    }
}
fn example_function() {
    unsafe {
        std::ptr::read(std::ptr::null());
    }
}

Compliant Example - Prose

First Example:
Since 0_u8 is defined to represent the false value of bool, this example is free of undefined behavior.

Second Example:
ptr points to a valid, aligned and properly initialized allocation.
Therefore, it satisfies all safety preconditions of :std:std::ptr::read and can be read without undefined behavior.

Compliant Example - Code

fn example_function() -> bool {
    unsafe {
        std::transmute<bool>(0_u8);
    }
}
fn example_function() {
    let ptr = Box::new(42).into_raw();
    unsafe { std::ptr::read(ptr); }
}

Metadata

Metadata

Assignees

Labels

category: requiredA coding guideline with category requiredchapter: unsafetycoding guidelineAn issue related to a suggestion for a coding guidelinedecidability: undecidableA coding guideline which cannot be checked automaticallyscope: systemA coding guideline that can be determined applied only when entire source is inspectedstatus: draft

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions