Search code examples
c++cpointersmallocallocation

What is the difference between these two lines of code


What is the difference between:

p = (int*) malloc (5*sizeof(int));

vs

int *ptr = new int[5];

Is the top one C's version of memory allocation for a pointer to point to create a spot in memory for 5 integers? Then the bottom is C++'s version? Where do they appear in memory (if they do).


Solution

  • Both allocates size bytes of uninitialized storage and return a pointer to it. Both snippets works on C++, but the new one is exclusive for C++. Implementation of both depends on the compiler. When using malloc() function, always use free() function to free memory. When using new operator, always use delete operator to free memory. Never mix the pairs.

    new can offer some other features like being overloaded and call a non-primitive type constructor. See.

    In both examples you gave, memory will be allocated sequentially.