pingcap / pingcap/tiflash

Introduce `not_null` and a safe `std::optional` to avoid dereferencing nullptrs

Open
#8,500 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

type/enhancement
Dominant language
C++
Stars
1k
Forks
423
Avg merge
1d 15h
Merged PRs (30d)
24

Description

Enhancement

Currently, codes are prone to panic / UB if:

  1. We derefing an std::shared_ptr of nullptr.
  2. We derefing an std::optional of nullopt.

For example

#include <optional>
#include <cstring>
#include <cstdio>
#include <memory>

struct I {
    int get() { return 1; }
};

void f() {
    try {
        std::optional<std::shared_ptr<I>> x = std::nullopt;
        printf("%d\n", (*x)->get()); // -----> UB, and returns wrong result rather than panic on g++
    }
    catch (std::bad_optional_access & e) {
        printf("it throws in f\n");
    }
}

void g() {
    try {
        int * x = nullptr;
        printf("%d\n", *x); // -----> UB and panics
    } catch (...){
        printf("it throws in g\n");
    }
}

If these happens, it will be segment fault, and it is very hard to find what causes the panic. https://github.com/pingcap/tiflash/issues/8249 is an example. It is also not worthy to check by if everytime we try to deref. For example, if the API provider always returns a valid ptr, it can use not_null.

So I suggest we introduce not_null and safe_option in TiFlash.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the issue's null-dereference examples, the linked Microsoft GSL not_null implementation, and the linked safe_option proposal. Clarify the desired APIs, ownership and failure behavior with maintainers; done requires an agreed scope and validation for both shared-pointer and optional cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.