A smart pointer without a deleter owns memory or a stream from the C library, which it releases with delete

tx0/cpp:smart-pointer-of-c-allocationrecommendedwarningreliability/memory-safetydepth fastbug, cwe-762

What it finds

std::unique_ptr<char> name(strdup(text)); or std::shared_ptr<FILE> f(fopen(path, "r"));: without a deleter of its own, a smart pointer releases what it owns with delete, but memory from malloc, calloc, realloc or strdup must be released with free, and a stream from fopen with fclose. Releasing it with delete is undefined, and a stream is never flushed or closed.

The rule looks at declarations of std::unique_ptr with a single template argument and of std::shared_ptr given a single constructor argument, and at reset of a variable so declared, when the pointer comes straight from one of the functions of the C library named above that the file does not declare itself.

From the rule's source, smart_pointer_of_c_allocation.rs.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/cpp:smart-pointer-of-c-allocation" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/cpp:smart-pointer-of-c-allocation] reason="..."

tx0 explain tx0/cpp:smart-pointer-of-c-allocation shows the same in the terminal. Found a false positive? Report it.