Sobes.tech
Junior — Middle

What are the differences between malloc and new functions in dynamic memory management?

sobes.tech AI

Answer from AI

malloc and new are different memory allocation mechanisms used in C and C++ respectively, with several differences:

  • malloc (C)

    • Allocates a block of memory of a specified size in bytes.
    • Returns a void* pointer, which must be explicitly cast to the desired type.
    • Does not call object constructors.
    • Does not initialize the memory (content is undefined).
    • Memory is freed using free().
  • new (C++)

    • Allocates memory and simultaneously calls the constructor of the object.
    • Returns a pointer of the appropriate type, no cast needed.
    • Initializes the object according to its constructor.
    • Memory is freed and destructor called via delete.

Example:

// malloc
int* p1 = (int*)malloc(sizeof(int));
*p1 = 42; // memory is uninitialized, needs explicit assignment
free(p1);

// new
int* p2 = new int(42); // memory allocated and initialized with value 42
delete p2;

Thus, new is safer and more convenient for working with objects in C++, as it manages initialization and constructor calls, whereas malloc is a low-level memory allocation method without initialization.