Skip to content

R crashing after successfully running compiled code

8 messages · michael.weylandt at gmail.com (R. Michael Weylandt, Duncan Murdoch, Brian Ripley +3 more

On Oct 31, 2012, at 3:13 AM, Adam Clark <atclark at umn.edu> wrote:

            
Hi Adam,

Can you make a minimal reproducible example of your C sources available? I'm relatively certain that the problem is in the memory management therein, but I obviously can't say more without seeing the code. 

Michael
#
On 12-10-30 11:13 PM, Adam Clark wrote:
I think your C code has a bug in it.  The bug might go away when you 
rewrite the function to work within the .Call convention, but it is 
probably easier to find the bug and fix it with the current code.

Things to look for:

Are you fully allocating all arrays in R before passing them to C?  The 
C code receives a pointer and will happily write to it, whether that 
makes sense or not.

Are you careful with your limits on vectors?  In R, a vector is indexed 
from 1 to n, but the same vector in C is indexed from 0 to n-1.  If the 
C code writes to entry n, that will eventually cause problems.

Are you allocating memory in your C code?  There are several ways to do 
that, depending on how you want it managed.  If you do it one way and 
expect it to be managed in a different way, you'll get problems.

Duncan Murdoch
#
On Wed, 31 Oct 2012, Duncan Murdoch wrote:

            
Using R-devel and the following new feature

     ? There is a new option, options(CBoundsCheck=), which controls how
       .C() and .Fortran() pass arguments to compiled code.  If true
       (which can be enabled by setting the environment variable
       R_C_BOUNDS_CHECK to yes), raw, integer, double and complex
       arguments are always copied, and checked for writing off either
       end of the array on return from the compiled code (when a second
       copy is made).  This also checks individual elements of character
       vectors passed to .C().

       This is not intended for routine use, but can be very helpful in
       finding segfaults in package code.

makes checking these two points a lot easier.
If you can run your code under valgrind (see 'Writing R Extensions') 
you will usually get pointed to the exact cause.  But that's for 
Linux, and with some care MacOS X.
#
As long as you use C (or C++ or Fortran ...), using memory that
you don't own is possible.  This is one reason people use languages
like R.

(If you program microprocessors or write operating system code
then C's willingness to let you read or write any at address is essential.)

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
#

        
On Oct 31, 2012, at 9:04 AM, William Dunlap wrote:

            
This seems suitable for the fortunes collection. Any seconds to this nomination?