Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Sunday, September 29, 2024

Operators in C++ (new, delete)

 
Operators in C++ (new, delete)

In C++, operators such as new and delete are critical for dynamic memory management. They allow programmers to allocate and deallocate memory during runtime. These operators are fundamental when working with objects or arrays whose size or lifetime cannot be determined at compile time.

1. new Operator:

  • Purpose: Allocates memory dynamically from the heap for a single object or an array of objects.

  • Syntax:

    int* ptr = new int;          // Allocates memory for a single int

    int* arr = new int[10];      // Allocates memory for an array of 10 integers

    MyClass* obj = new MyClass;  // Allocates memory for an object of MyClass

  • Returns: A pointer to the allocated memory.
  • Initialization: The new operator can initialize the allocated memory:

    int* ptr = new int(5);  // Allocates and initializes an int to 5

  • Throwing Exceptions: If memory allocation fails, the new operator throws a std::bad_alloc exception. To avoid this, you can use the nothrow version:
    int* ptr = new(std::nothrow) int;
    if (ptr == nullptr) {
      // Handle the failure
    }


    2. delete Operator:

    • Purpose: Deallocates memory allocated by the new operator to free up resources.

    • Syntax:

      delete ptr;      // Deletes the memory allocated for a single object

      delete[] arr;    // Deletes the memory allocated for an array of objects

    • Usage: If the memory was allocated for a single object, use delete. If it was allocated for an array of objects, use delete[].
    • Avoiding Undefined Behavior: If memory is deallocated using delete but was allocated using new[], or vice versa, it results in undefined behavior.


  • Program : 

  • #include <iostream>

    using namespace std;

    int main() {

        // Scalar allocation using new

        int* p = new int;  // Allocates memory for a single integer

        *p = 10;           // Assigns value to the allocated memory

        cout << "Value of p before delete: " << *p << endl;

       // Deallocate memory for the single integer

        delete p;

        // Attempt to access the value after deletion (undefined behavior)

        cout << "Value of p after delete: " << *p << endl;

       

        return 0;

    }


No comments:

Post a Comment