What's the equivalent of new/delete of C++ in C?
Or it's the same in C/C++?
delete keyword in C++ Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. Delete can be used by either using Delete operator or Delete [ ] operator. New operator is used for dynamic memory allocation which puts variables on heap memory.
These operators allocate memory for objects from a pool called the free store (also known as the heap). The new operator calls the special function operator new , and the delete operator calls the special function operator delete .
malloc(): It is a C library function that can also be used in C++, while the “new” operator is specific for C++ only. Both malloc() and new are used to allocate the memory dynamically in heap. But “new” does call the constructor of a class whereas “malloc()” does not.
No, new and delete are not supported in C.
There's no new
/delete
expression in C.
The closest equivalent are the malloc
and free
functions, if you ignore the constructors/destructors and type safety.
#include <stdlib.h> int* p = malloc(sizeof(*p)); // int* p = new int; ... free(p); // delete p; int* a = malloc(12*sizeof(*a)); // int* a = new int[12]; ... free(a); // delete[] a;
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