C++ Interview Questions

22 Questions
C++ Programming

C++ Programming

Embedded SystemsIoTOther

Question 12

What are the differences between 'new' and 'malloc' in C++? Provide examples of how and when to use each.

Answer:

In C++, new and malloc are both used for dynamic memory allocation, but they have significant differences in terms of functionality, syntax, and behavior.

Key Differences:

  1. Type Safety:

    • new: Provides type safety. It returns a pointer of the appropriate type, eliminating the need for explicit casting.
    • malloc: Does not provide type safety. It returns a void* pointer, which must be explicitly cast to the appropriate type.
    int* ptr1 = new int;     // Type-safe allocation
    int* ptr2 = (int*)malloc(sizeof(int)); // Requires casting
  2. Initialization:

    • new: Calls the constructor for objects and initializes the allocated memory.
    • malloc: Does not call constructors. It simply allocates a block of memory and leaves it uninitialized.
    struct MyStruct {
        int x;
        MyStruct() : x(10) {}
    };
    
    MyStruct* obj1 = new MyStruct(); // Constructor is called, x is initialized to 10
    MyStruct* obj2 = (MyStruct*)malloc(sizeof(MyStruct)); // No constructor call, x is uninitialized
  3. Deallocation:

    • new: Memory allocated with new should be deallocated using delete.
    • malloc: Memory allocated with malloc should be deallocated using free.
    delete ptr1;
    free(ptr2);
  4. Handling Non-Primitive Types:

    • new: Can be used for both primitive and non-primitive types, and it correctly handles constructors and destructors.
    • malloc: Primarily used for primitive types and raw memory allocation. It does not handle constructors or destructors.

Examples:

  1. Using new and delete:

    #include <iostream>
    
    class MyClass {
    public:
        MyClass() { std::cout << "Constructor called\n"; }
        ~MyClass() { std::cout << "Destructor called\n"; }
    };
    
    int main() {
        MyClass* obj = new MyClass(); // Constructor is called
        delete obj; // Destructor is called
        return 0;
    }
  2. Using malloc and free:

    #include <iostream>
    #include <cstdlib>
    
    int main() {
        int* arr = (int*)malloc(5 * sizeof(int)); // Allocates memory for an array of 5 integers
        if (arr != nullptr) {
            for (int i = 0; i < 5; ++i) {
                arr[i] = i * 2;
            }
            for (int i = 0; i < 5; ++i) {
                std::cout << arr[i] << " ";
            }
            free(arr); // Deallocates the memory
        }
        return 0;
    }

When to Use Each:

  • new: Use new when you need to allocate memory for objects and ensure that their constructors are called. This is typically the preferred method in C++ for dynamic memory allocation due to its type safety and constructor/destructor handling.
  • malloc: Use malloc when you need to allocate raw memory without the need for constructors, or when working with C code or libraries that require it. It is less commonly used in modern C++ code due to the lack of type safety and initialization.

Summary:
new and malloc both serve the purpose of dynamic memory allocation in C++, but they differ in type safety, initialization, and handling of constructors and destructors. new is generally preferred in C++ due to its type safety and ability to call constructors and destructors, making it more suitable for object-oriented programming. malloc is used for raw memory allocation and is more common in C or mixed C/C++ codebases.

Recent job openings