Sanitizing memory management in Go + SWIG + C++ code

Viewed 312

I'm using a C++ library from Go via SWIG. SWIG does not take care of memory management, so the Go side looks something like this:

f := NewFoo()
defer DeleteFoo(f)

It's easy enough to call DeleteFoo(f) when I created f, but it's easy to omit it for return values from C++ functions.

I want to automatically check that my code does the right thing.

I see Address Sanitizer is implemented for GCC and Clang and it sounds like the right thing. But I can't find a clear recipe for how I would enable it for my go test command.

2 Answers

I think CC="clang -fsanitize=address" go test or CC="gcc -fsanitize=address" go test should work.

Defer can be very useful in work within the block (functions etc...). However, this is not always enough.
What you need runtime.SetFinalizer

Directly, I don't think you can check the memory status of anything else with Go. (So memory allocated in C or C++.)

If I were you, I would compile part of C code as shared. It would be easy for me to check this later with tools like clang. If your C code shows no problems, there is no way you can interfere with Go's gc.

Related