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

httpinterpret picture httpinterpret · May 15, 2010 · Viewed 76.6k times · Source

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

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

Answer

kennytm picture kennytm · May 15, 2010

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;