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);
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With