Is it safe to transfer memory allocated with "new" to C libraries?

I know that new delete are incompatible with malloc free .

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

What could be wrong when using new instead of malloc when I transfer memory to the 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); } 
+5
source share
3 answers

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

As long as you map new to delete , new[] to delete[] and malloc / calloc using free (also realloc ), you're fine.

If you think about it, even C allocates memory in different places, and it works fine - if the 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); 
+11
source

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

Not at all. The memory is the same, so if you provide a safe way to free up memory, you can transfer that memory to the C library.

 int *p = new int(42); lib_func(p); delete p; 

Here is another example:

 extern "C" { int* make_buffer(size_t sz) { return new int[sz]; } void use_buffer(int* buf) { ... // do something } void free_buffer(int* buf) { delete[] buf; } } 

The above code allows your C code to request dynamically allocated memory from your C ++ library.

+8
source

This memory is like any other, so it is safe until the C library is free .

Note that in your example, you can also use memory on the stack that does not have allocation or deallocation functions:

 void func() { int p; lib_func(&p); } 
+4
source

Source: https://habr.com/ru/post/1213174/


All Articles