Software Development Exam  >  Software Development Notes  >  DSA in C++  >  New and Delete Operators For Dynamic Memory

New and Delete Operators For Dynamic Memory | DSA in C++ - Software Development PDF Download

Introduction

In the world of programming, managing memory dynamically is a crucial aspect of creating efficient and flexible applications. In C++, the "new" and "delete" operators play a vital role in allocating and releasing memory dynamically. This article aims to provide a beginner-friendly guide to understanding these operators, their usage, and common scenarios where they are employed. We will explore various examples and code snippets to demonstrate their practical implementation.

Basics of Dynamic Memory Allocation

In C++, memory can be allocated either statically or dynamically. Statically allocated memory is determined at compile-time, while dynamic memory allocation enables the allocation and deallocation of memory during runtime. The "new" and "delete" operators are used for this purpose.

The "new" Operator

The "new" operator is used to allocate memory dynamically. It requests memory from the system and returns the address of the allocated memory. Here are two common use cases for the "new" operator:

Allocating Memory for a Single Object

To allocate memory for a single object, we can use the "new" operator as follows:

int* ptr = new int;

*ptr = 42;

In this example, we allocate memory for an integer and assign the value 42 to it. The pointer 'ptr' now points to the dynamically allocated memory location.

Allocating Memory for Arrays

The "new" operator can also be used to allocate memory for arrays. We specify the array size in square brackets:

int* arr = new int[5];

In this case, we allocate memory for an array of five integers. The pointer arr points to the beginning of the allocated memory block.

The "delete" Operator

The "delete" operator is used to release memory allocated dynamically using the "new" operator. It helps prevent memory leaks and ensures proper resource management. Here are two common scenarios for using the "delete" operator:

Deleting a Single Object

To deallocate memory for a single object, we use the "delete" operator as follows:

int* ptr = new int;

*ptr = 42;

// Perform operations with ptr...

delete ptr;

In this example, after performing necessary operations, we release the memory allocated for the integer pointed to by 'ptr' using the "delete" operator.

Deleting an Array

When deleting a dynamically allocated array, we use the "delete[]" operator to release the memory:

int* arr = new int[5];

// Perform operations with arr...

delete[] arr;

Here, the "delete[]" operator ensures that the entire array is deallocated, preventing memory leaks.

Memory Leaks and Proper Resource Management

Memory leaks occur when dynamically allocated memory is not properly deallocated, leading to a loss of available memory resources. To avoid memory leaks, it's essential to pair each "new" operation with the corresponding "delete" operation, ensuring that all dynamically allocated memory is freed when it's no longer needed.

Example: Memory Leak

void allocateMemory() {

    int* ptr = new int;

    *ptr = 42;

} // Memory leak - ptr is not deleted

In this example, the dynamically allocated memory is not freed, resulting in a memory leak. To fix this, we need to add 'delete ptr'; before the function ends.

Sample Problems

Problems 1: Write a program that dynamically allocates memory for an array of integers of size N. Read N from the user and populate the array with the first N even numbers. Print the array.

#include <iostream>

int main() {

    int N;

    std::cout << "Enter the number of elements: ";

    std::cin >> N;

    int* arr = new int[N];

    for (int i = 0; i < N; i++) {

        arr[i] = (i + 1) * 2;

    }

    std::cout << "The array of even numbers is: ";

    for (int i = 0; i < N; i++) {

        std::cout << arr[i] << " ";

    }

    delete[] arr;

    return 0;

}

Problems 2: Write a program that dynamically allocates memory for a string and reads input from the user. Print the string in reverse order.

#include <iostream>

#include <cstring>

int main() {

    char* str = new char[100];

    std::cout << "Enter a string: ";

    std::cin.getline(str, 100);

    int length = std::strlen(str);

    std::cout << "The string in reverse is: ";

    for (int i = length - 1; i >= 0; i--) {

        std::cout << str[i];

    }

    delete[] str;

    return 0;

}

Conclusion

Dynamic memory allocation is a powerful feature of C++, allowing programs to manage memory efficiently during runtime. The "new" and "delete" operators play a crucial role in allocating and releasing memory. By understanding their usage and employing proper resource management techniques, you can prevent memory leaks and build robust and efficient applications.
Remember to always pair each "new" operation with the corresponding "delete" operation to ensure the proper deallocation of dynamically allocated memory. With practice and a solid understanding of dynamic memory management, you'll be well-equipped to create flexible and memory-efficient programs in C++.

The document New and Delete Operators For Dynamic Memory | DSA in C++ - Software Development is a part of the Software Development Course DSA in C++.
All you need of Software Development at this link: Software Development
153 videos|115 docs|24 tests

Top Courses for Software Development

153 videos|115 docs|24 tests
Download as PDF
Explore Courses for Software Development exam

Top Courses for Software Development

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

New and Delete Operators For Dynamic Memory | DSA in C++ - Software Development

,

video lectures

,

Objective type Questions

,

New and Delete Operators For Dynamic Memory | DSA in C++ - Software Development

,

Free

,

past year papers

,

MCQs

,

practice quizzes

,

Exam

,

ppt

,

Sample Paper

,

Previous Year Questions with Solutions

,

Important questions

,

shortcuts and tricks

,

mock tests for examination

,

Summary

,

New and Delete Operators For Dynamic Memory | DSA in C++ - Software Development

,

pdf

,

study material

,

Extra Questions

,

Viva Questions

,

Semester Notes

;