Search code examples
c++cnew-operatordelete-operator

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++?


Solution

  • 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;