Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to pass memory allocated using "new" to C libraries?

I know that new delete are incombatible with malloc free.

Does that mean that I should avoid using new for memory that will be used by a C library?

What are things that can go wrong when using new instead of malloc when I will pass the memory to a C library?

void func()
{
    int *p = new int(42);

    // Should I insist on using malloc for p if this function is a part
    // of a C library?
    lib_func(p);
}
like image 446
wefwefa3 Avatar asked Nov 30 '22 10:11

wefwefa3


1 Answers

Memory is memory, and it does not matter how it was allocated.

As long as you're matching new with delete, new[] with delete[] and malloc/calloc with free (also realloc), you're okay.

If you think about it, even C allocates memory in different places, and it works fine --- if a library expects an int, you can allocate it either on the stack, or on the heap (or in some global storage):

int a;
int* b = malloc(sizeof(int));
static int c;

some_func(&a);
some_func(b);
some_func(&c);
like image 193
Tim Čas Avatar answered Dec 04 '22 21:12

Tim Čas