2

I need to have int** to pass to API function call written in C. Based on the description of the API, it uses malloc to allocate memory, and it requires the user to free the memory after it is returned.

How to create a std::unique_ptr<int*> ? If I have one, does .get() function return a int**. I was thinking if I could wrap my pointer in a unique_ptr and make sure it will be freed when out of scope. I am not sure if the following implementation ensures that memory is freed after allocation? Is there a better way of achieving this?

int ** get_double_ptr()
{
    int ** ids;
    return ids;
}

int main(int argc, char **argv)
{

    std::unique_ptr<int*> i_ptr(get_double_ptr());

    int ** idx = i_ptr.get();
    // allocate ids using malloc ....

}

The C function is declared as below:

int MeshToNodal(int *ne, int *nn, int *eptr, int *eind, int *numflag,
int **xadj, int **adjncy)
apramc
  • 1,346
  • 1
  • 15
  • 30
  • 1
    @tilz0R: The user is asking about interfacing with C code. That involves knowing about C code. – Nicol Bolas Jun 21 '17 at 14:48
  • I am calling a API that is written in C from a c++ code – apramc Jun 21 '17 at 14:48
  • The pointer you gave `unique_ptr` to `delete` later is not the pointer that was allocated. Also using `delete` when you were supposed to use `free` is not correct. – nwp Jun 21 '17 at 14:48
  • Could you add the declaration of the `C` function you are trying to call? Is it a `int**` because it is going to allocate an array of `int` for you, or is int a `int**` because it is going to use an array of pointer you allocated before? – Holt Jun 21 '17 at 14:49
  • Your question is contradicted: if you pass array, then memory already allocated, if memory is allocated inside C call, then you pass pointer, not array. You need to be more clear. – Slava Jun 21 '17 at 14:51
  • Still the tag [tag:c] should be appropriate when the question is about *interfacing* with C code. Don't be too quick removing tags. –  Jun 21 '17 at 14:52

0 Answers0