Dynamic Memory Allocation (new and delete)

Introduction

C++ में memory को दो तरीकों से allocate किया जा सकता है — static और dynamic। Static memory allocation compile time पर होता है, जबकि dynamic memory allocation run time पर होता है।

जब program के execution के दौरान memory की आवश्यकता बदलती रहती है, तब dynamic memory allocation का उपयोग किया जाता है। इससे program को flexibility मिलती है और memory का efficient उपयोग किया जा सकता है।

C++ में dynamic memory allocation के लिए new और delete operators का उपयोग किया जाता है।

Definition

new Operator

new operator का उपयोग run time पर memory allocate करने के लिए किया जाता है। यह allocated memory का address return करता है।

delete Operator

delete operator का उपयोग dynamically allocated memory को free करने के लिए किया जाता है, ताकि memory leak न हो।

new का Syntax

pointer = new dataType;

delete का Syntax

delete pointer;

Example (Single Variable)

#include <iostream>
using namespace std;

int main() {
int *ptr;
ptr = new int; // memory allocation

*ptr = 10;

cout << "Value: " << *ptr << endl;

delete ptr; // memory free

return 0;
}

Output:

Value: 10

Array के लिए Dynamic Allocation

#include <iostream>
using namespace std;

int main() {
int *arr;

arr = new int[3]; // array allocation

arr[0] = 5;
arr[1] = 10;
arr[2] = 15;

cout << arr[0] << " " << arr[1] << " " << arr[2];

delete[] arr; // array free

return 0;
}

Output:

5 10 15

Objects के लिए Dynamic Allocation

#include <iostream>
using namespace std;

class Demo {
public:
int x;

void setValue(int v) {
x = v;
}
void show() {
cout << "Value: " << x;
}
};

int main() {
Demo *d;

d = new Demo(); // object allocation

d->setValue(25);
d->show();

delete d; // memory free

return 0;
}

Output:

Value: 25

Working को समझना

new → memory allocate करता है

  • pointer उस memory का address store करता है
  • delete → memory को free करता है
  • arrays के लिए delete[] उपयोग होता है

Dynamic Memory Allocation के लाभ

  • Memory का efficient उपयोग
  • Run time flexibility
  • Large data handling में सहायक
  • Program को adaptable बनाता है

Important Points

  • new हमेशा pointer return करता है
  • delete का उपयोग करना जरूरी है, नहीं तो memory leak हो सकता है
  • array के लिए delete[] उपयोग करें
  • object के लिए delete उपयोग करें

निष्कर्ष

Dynamic Memory Allocation C++ में एक महत्वपूर्ण feature है जो program को run time पर memory manage करने की सुविधा देता है। new और delete operators के माध्यम से memory को allocate और free किया जाता है, जिससे program efficient और flexible बनता है।

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top