spdlog icon indicating copy to clipboard operation
spdlog copied to clipboard

Initialize function-local static variables using "T& t = *new T"

Open lixingcong opened this issue 1 year ago • 4 comments

It would be safer if init the static object with reference according to Google C++ Style Guide.

I compile the static lib, link to my program, then get segmentation fault on calling mdc::get_context(). After applying these patches the bug was gone. :100:

lixingcong avatar Aug 17 '24 14:08 lixingcong

Thanks but now tests fails with “LeakSanitizer: detected memory leaks”. A possible solution would be to delete those objects in spdlog::shutdown() and call it at the end of tests.

gabime avatar Aug 17 '24 15:08 gabime

So hard to free memory of thread_local object created by T& t=*new T

#include <iostream>
#include <thread>

struct A {
	A(int i)
	    : a(i)
	{
		std::cout << "ctor(), i=" << a << std::endl;
	}

	~A()
	{
		std::cout << "dtor(), i=" << a << std::endl;
	}

	const int a;
};

static A& get_a()
{
	static thread_local A& a = *new A(8);
	static thread_local A  b(100);
	return a;
}

int main()
{
	std::thread t([]() { get_a(); });
	t.join();
	return 0;
}

Compile with gcc 11 it got weird print:

ctor(), i=8
ctor(), i=100
dtor(), i=100

That is why LeakSanitizer tell us memory leak happened.

lixingcong avatar Aug 19 '24 08:08 lixingcong

This has to solved somehow

gabime avatar Aug 19 '24 16:08 gabime

I tested this PR. The first commit does fix the segmentation fault, but the second doesn't.

moi15moi avatar Oct 29 '25 18:10 moi15moi