facebook / facebook/folly

Double free error when mixing c++20 project with folly built using c++17

Open
#2,477 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
30.5k
Forks
5.9k
PR merge metrics
No merged PRs in 30d

Description

If folly is built with c++17, but the project using folly is built using c++20, when jemalloc is enabled, `folly::usingJEMalloc()` has double free error at [folly/memory/Malloc.h#L192](https://github.com/facebook/folly/blob/470fa8d7c9772af2833d25f4c2bafa0726f5278a/folly/memory/Malloc.h#L192).

Compiler is clang 18.

Minimal code to reproduce:

```
int main(int argc, char **argv) {
const folly::Init init(&argc, &argv);
std::cout << "use jemalloc: " << folly::usingJEMalloc() << std::endl;
return 0;
}
```
`folly::usingJEMalloc()` should return true but actually it returns false.

This is because template class `FastStaticBool` is initialized twice using different definitions under c++17 and c++20 (this violates ODR and causes UB). As a result, `Initializer::operator()()` is called twice. For reasons I cannot understand, `ptr` is declared as static at [folly/memory/Malloc.h#L186](https://github.com/facebook/folly/blob/470fa8d7c9772af2833d25f4c2bafa0726f5278a/folly/memory/Malloc.h#L186). It's allocated once but freed twice.

This section of code is excluded if `FOLLY_SANITIZE` defined, which makes it escaped from sanitizer checks.

Apart from that strange `static` declaration on `ptr`, I think we should avoid the template being defined differently. A possible fix is to move `FOLLY_CPLUSPLUS` macro from `Portability.h` to `folly-config.h`, and set its value to the C++ version used when compiling folly.

Contributor guide

Open the contributing guide

Research direction

Reproduce the issue with folly built using C++17, a C++20 consumer, clang 18, and jemalloc, then inspect folly/memory/Malloc.h around lines 186 and 192. Read Portability.h and folly-config.h to trace how FOLLY_CPLUSPLUS affects FastStaticBool. Done means the mixed-standard program returns true from folly::usingJEMalloc() without a double free.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.