Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent of new/delete of C++ in C?

What's the equivalent of new/delete of C++ in C?

Or it's the same in C/C++?

like image 358
httpinterpret Avatar asked May 15 '10 09:05

httpinterpret


People also ask

What is delete in 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.

What is new and delete operator?

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 .

What is difference between new () and malloc ()?

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.

Does C have new keyword?

No, new and delete are not supported in C.


1 Answers

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; 
like image 81
kennytm Avatar answered Oct 08 '22 21:10

kennytm