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.

This doc is part of
153 videos|115 docs|24 tests
Join course for free

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.

Download the notes
New and Delete Operators For Dynamic Memory
Download as PDF
Download as PDF

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.

Take a Practice Test
Test yourself on topics from Software Development exam
Practice Now
Practice Now

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
Are you preparing for Software Development Exam? Then you should check out the best video lectures, notes, free mock test series, crash course and much more provided by EduRev. You also get your detailed analysis and report cards along with 24x7 doubt solving for you to excel in Software Development exam. So join EduRev now and revolutionise the way you learn!
Sign up for Free Download App for Free
153 videos|115 docs|24 tests

Up next

153 videos|115 docs|24 tests
Download as PDF

Up next

Explore Courses for Software Development exam
Related Searches

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

,

Extra Questions

,

shortcuts and tricks

,

study material

,

past year papers

,

Objective type Questions

,

Previous Year Questions with Solutions

,

practice quizzes

,

pdf

,

Semester Notes

,

ppt

,

Viva Questions

,

mock tests for examination

,

Summary

,

Sample Paper

,

Exam

,

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

,

video lectures

,

Important questions

,

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

,

Free

,

MCQs

;