0

I'm studying Rcpp and encountered an interesting but (might be) weird issue.

Essentially int *a = new int(1); is not working in the same way as:

  int b = 1;
  int *a;
  a = &b;

Any ideas why? Full code below. If I uncomment int *a = new int(1); then the code below works as intended.

#include <Rcpp.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace Rcpp;
using namespace std;

// [[Rcpp::export]]
int bar(SEXP a) {
  Rcpp::XPtr<int> ptr(a);
  int b = *ptr;

  cout << b;
  return (b);
}


// [[Rcpp::export]]
SEXP foo() {
  // int *a = new int(1);

  int b = 1;
  int *a;
  a = &b;

  cout << *a;
  Rcpp::XPtr<int> ptr(a);
  return ptr;
}

Then in R: I was hoping to get b = 1.

> a = foo()
1
> b = bar(a)
0
> b
[1] 0

=========================================================================== Edit: My question actually originates from Pass a c++ object as a pointer an reuse in another function in Rcpp, but when I wish to test c-style pointer below

  int b = 1;
  int *a;
  a = &b;

to replace int *a = new int(1);, it's simply not working as intended. That's why I asked this question here.

Min
  • 179
  • 9
  • It's not working the same since one is a pointer to a heap allocated int and the other is a pointer to a int on the stack. Very different things. Especially when it comes to cleanup/deleting that int. One needs an explicit `delete` the other just goes out of scope and is destroyed (and the pointer to it is now garbage). – Jesper Juhl Oct 14 '18 at 14:09
  • The `.Call()` interface to R only allows `SEXP` types; see the R documentation as well as the Rcpp documentation for copious details. – Dirk Eddelbuettel Oct 14 '18 at 15:29
  • @JesperJuhl Thanks Jesper. I guess this is precisely the reason. without `new`, variables are in stack, which is then deleted once the function is finished in R-counterpart. Hence the pointer actually points to the default value 0, not 1... – Min Oct 14 '18 at 15:30
  • @DirkEddelbuettel Thanks Dirk. Just had a look at R's API to C. If I wish to use c-style pointers, do I have to use PROTECT, otherwise R's garbage collector will delete them? BTW I don't think this question is duplicated though, the old question doesn't answer why c-style pointer can't be used – Min Oct 14 '18 at 15:35
  • 1
    You _could_ use the still-existing-but-discouraged `.C()` interface. Note that that pretty much precludes use of Rcpp. Also note that you _can_ get a C-style pointer from a C++ object, ie `&(x[0])` is the beginning the `std::vector` object. These are all elementary C/C++ question. There is nothing new or worthwhile for Rcpp here, really. – Dirk Eddelbuettel Oct 14 '18 at 15:51
  • 1
    There is no "default 0 value". An uninitialised variable has an *indeterminate* value. – Jesper Juhl Oct 14 '18 at 15:55
  • @JesperJuhl So returning 0 might be an undefined behaviour then... – Min Oct 14 '18 at 16:08
  • @Min - Yes. It might be. – Jesper Juhl Oct 14 '18 at 16:52

0 Answers0