[Rcpp-devel] Rcpp-devel] What is the best practice to expose a C structure from 3rd party library into R?

Steve Jaffe sjaffe at riskspan.com
Tue Jul 23 21:46:04 CEST 2013


On: Tuesday, July 23, 2013 1:14 PM
Dirk Eddelbuettel [mailto:edd at debian.org] wrote:

> > On 23 July 2013 at 11:50, Steve Jaffe wrote:
> > According to the C standard, it is safe to call free on a null pointer. 
> > Similarly, according to the C++ standard, it is safe to call 'delete' 
> > on a null pointer.
> > Thus there is no need ever to test a pointer for null before 
> > free-ing/delete-ing. 
> > ...
>  
> Thanks for the correction.  I obviously shouldn't have mixed malloc/free with
> new/delete in the discussion.
> 
> I rarely need to write code that uses new/delete these days as I much prefer
> to rely on STL containers -- a programming style advocated by just about
> every modern C++ text (incl Stroustrup, 2013, 4th ed).  And by just about all
> Rcpp examples we provide.   
> 
> Dirk

I agree that STL containers should be used whenever possible and new/delete avoided whenever possible.

However, there are times when explicit 'new' cannot be avoided (I'm now referring only to C++.) In those cases the best way to avoid the need for explicit memory management is to use an appropriate "smart pointer" such as boost::shared_ptr (std::shared_ptr as of C++11). Then one never has to explicitly call 'delete.'

To clarify, though: what I said originally about NULL pointers applies to both C (malloc/free) and C++ (new/delete). 

I know there is a lot of code where people check for null pointers before calling free or delete (I know -- I wrote a bunch of that code when I first started programming C/C++ :-) 

But it turns out that check is completely unnecessary. It is perfectly ok to call "free(0)" or "delete (char*)0" (although obviously no-one would write those explicitly.) This will *not* cause a core-dump (at least not with a standard-conforming compiler.) 

(I think the "legend" that it's bad to call 'free' on a null pointer may be based on some early C compilers, perhaps before the ANSI C standard...)

I apologize for belaboring the point; I'm doing so only because this seems to be something that is often misunderstood, especially by newcomers to C/C++; and such misunderstanding can lead to someone wasting time when looking for the cause of a crash.

References:
C: Kernighan and Ritchie, The C Programming Language (2nd Ed), Appx B:
"void free(void *p)
 free deallocates the space pointed to by p; it does nothing if p is NULL."
C++: http://www.parashift.com/c%2B%2B-faq-lite/delete-handles-null.html

Steve

Steve Jaffe
sjaffe at riskspan.com


More information about the Rcpp-devel mailing list