1

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).

Euxitheos
  • 325
  • 4
  • 15
  • depends on the implementation. The C++ library's default `operator new` might just call `malloc` under the hood, or it might not. It might also allocate extra space to track the array size, invisibly to the user program. – Chris Dodd Aug 23 '19 at 20:01
  • 2
    For `int`s, not a lot. But try doing that for non-POD types (over-simplifying, "types that have constructors") and the difference will be huge, since `malloc` does not know it should call the constructor in the first place. – Daniel Kamil Kozar Aug 23 '19 at 20:36

1 Answers1

1

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.

João Paulo
  • 6,300
  • 4
  • 51
  • 80
  • Are both allocated onto the heap? – Euxitheos Aug 23 '19 at 20:47
  • 1
    The dynamic memory is allocated on the heap and the pointer itself is allocated on the stack for both types of allocation. – João Paulo Aug 23 '19 at 20:48
  • 2
    And in the case of using `new[]`, always use `delete[]`, not `delete`. Of course, usually you should just avoid using `new[]`/`delete[]` altogether. – jamesdlin Aug 23 '19 at 20:51
  • So C++ operators, "new" and "delete" are used for allocating dynamic memory. While on the other hand in the C language, instead the functions malloc is used to allocate dynamic memory. I can use malloc in C++ and C but that is not the case for new/delete. – Euxitheos Aug 24 '19 at 21:22