[Rd] R extension memory leak detection question

Tomas Kalibera
Mon, 15 Mar 2021 08:27:00 -0000

On 3/12/21 7:43 PM, xiaoyan yu wrote:
> I am writing C++ program based on R extensions and also try to test the
> program with google address sanitizer.
>
> I thought if I don't protect the variable from the allocation API such
as
> Rf_allocVector, there will be a memory leak. However, the address sanitizer
> didn't report it. Is my understanding correct? Or I will see the memory
> leak only if I compile R source code with the address sanitizer.

Yes, you should use special options for compilation and linking to use
address sanitizer. See Writing R Extensions, section 4.3.3.

If you allocate an R object using Rf_allocVector(), but don't protect
it, it means this object is available for the garbage collector to
reclaim. So it is not a memory leak.

Memory leaks with a garbage collector are much less common than without,
because if the program loses a pointer to some piece of memory, that
piece will automatically be reclaimed (not leaked). Still, memory leaks
are possible if the program forgets about a pointer to some piece of
memory no longer needed, and keeps that pointer in say some global
structure. Such memory leaks would not be found using address sanitizer.

Address sanitizer/Undefined behavior sanitizer can sometimes find errors
caused by that the program forgets to protect an R object, but this is
relatively rare, as they don't understand R heap specifically, so you
cannot assume that if you create such example, the error will always be
found.

Best
Tomas

>
>   Please help!
>
> Thanks,
> Xiaoyan
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel