5

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Daniel Darabos
  • 26,991
  • 10
  • 102
  • 114

2 Answers2

0

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

lu4p
  • 46
  • 3
  • That fails to build. ``/usr/bin/ld: $WORK/b054/_cgo_main.o: in function `asan.module_ctor': _cgo_main.c:(.text+0x82): undefined reference to `__asan_init'`` Thanks for the answer, but I'll need a bit more handholding! – Daniel Darabos Dec 11 '20 at 17:01
0

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.

  • Thanks! I don't think `SetFinalizer` is a 100% reliable solution either. If it were, SWIG would set it up. See the comment from Ian in https://github.com/swig/swig/issues/289#issuecomment-79369481. In any case, this helps with writing good code. But I'm looking for a way to automatically check that the existing code is good. – Daniel Darabos Dec 12 '20 at 11:22
  • @Daniel Darabos `SetFinalizer` has no warranty. It is writtened in documents. Anyway, I want to say that you're thinking wrong. You can only examine Go's memory on Go. Go's tests explain what should work correctly and other details. – SeanTolstoyevski Dec 12 '20 at 15:57