0

I've written an R package, but when running certain operations, it crashes R. The packages includes Rcpp routines, which is where I suspect this is happening. Strangely, running the same operation doesn't consistently cause a crash. Sometimes it does, sometimes it doesn't. Does anyone have suggestions for how to debug such a problem? I'm on Windows 10, running R studio with R v4.0.5.

Thanks in advance.

  • If you think the issue is your C++ code, maybe use valgrind? http://kevinushey.github.io/blog/2015/04/05/debugging-with-valgrind/ – Roland Jun 08 '21 at 09:09

2 Answers2

0

The manual Writing R Extensions recommends two tools: Valgrind and AddressSanitizer

  1. Use a recent Linux version (Fedora recommended), e.g. in a virtual machine
  2. Install the necessary tools
  3. Compile R-devel with valgrind instrumentation
  4. Compile the package
  5. Check suspect functions or the whole package with valgrind enabled

The official manual (see above) contains several links, and you will find more with your favorite search engine. Here one example: https://medium.com/@danielvfryer/valgrind-memcheck-with-r-a-quick-and-dirty-guide-d64567394c57

Furthermore, SO contains also some excellent guides. Just search for Valgrind and you find for example: How do I use valgrind to find memory leaks?

tpetzoldt
  • 5,338
  • 2
  • 12
  • 29
0

There is a (by now classic) video from the Bioconductor team describing a complete debug session of compiled R package code -- I highly recommend it.

As an aside I disagree with the previous answer and its 'Fedora recommended'. Any Linux distribution with the tools will do, they all work nicely in Docker too (and we have Rocker as well). I have worked for maybe 25 years with R and never used Fedora. The R manuals are generally also pretty clear about not recommending any one distribution, and R Core tests on several. The exact wording in Section 4.3.2 "Using valgrind" in the Writing R Extensions manual is

If you have access to Linux on a common CPU type or supported versions of macOS or Solaris you can use 'valgrind' (https://www.valgrind.org/, pronounced to rhyme with 'tinned') to check for possible problems. )

and I concur with that recommendation of 'any system'. Windows too can run gdb.

To use valgrind, instrumentation is helpful but not required. So the simplest case (to me) is still docker run --rm -ti r-base bash to open a bash shell in a Docker container with R (under Debian) where one could then install valgrind. That still requires understanding of Linux, and Docker, so it is not a given.

So back to the basic question: gdb as well as print statements can go a long in narrowing the issue down. First step, as always, is to reliably reproduce the issue.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725