📌 C++ Memory Allocation and deallocation: Static vs Dynamic
📌 C++ Memory Allocation and deallocation: Static vs Dynamic
In C++, memory allocation refers to reserving memory during program execution.
There are two primary types:
🔹 a) Static Memory Allocation
-
Memory is allocated at compile-time.
-
Fixed size and scope-based.
-
Used for local and global variables.
💡 Example:
🔸 b) Dynamic Memory Allocation
-
Memory is allocated during runtime using pointers.
-
Allows flexible memory use.
-
Requires manual deallocation to avoid memory leaks.
🛠️ Key Operators:
Memory deallocation (delete) in C++ means releasing memory that was previously allocated using new or new[].
This is done using:
- delete → for a single variable
- delete[] → for an array
-
new → allocates memory
New → for a single variable
syntsx: data_type *ptr_name=new data_type;
New → for array
syntax: data_type *array_name = new data_type[size];
-
delete → deallocates memory
delete → for a single variable
syntax: delete ptr_name;
delete[] → for an array
syntax: delete [ ] array_name;
✅ Example (Single Variable Allocation):
Example 2:
using namespace std;
int main()
{
int num1,num2;
int *sum=new int;
cout<<“Enter two numbers “<<endl;
cin>>num1>>num2;
*sum=num1+num2;
cout<<“Total is “<<*sum;
delete sum;
return 0;
}
using namespace std;
int main()
{
int *num1=new int;
int *num2=new int;
int *sum=new int;
cout<<“Enter two numbers “<<endl;
cin>>*num1>>*num2;
*sum=*num1+*num2;
cout<<“Total is “<<*sum;
delete sum;
return 0;
}
✅ Example (Dynamic Array Allocation):
⚠️ Reminder:
-
Always use delete for memory allocated with new.
-
Always use delete[] for memory allocated with new[].
🛠️For more computer skills, click here
PhD Mobility Exchange to Italy – Apply Now | University of Rwanda
BREAKING NEWS: American Robert Prevost Elected as New Pope, Takes Name Leo XIV
What Is Stress & How to Handle It Like a Professional | Top Tips & Foods
Job Opportunity: Local Project Manager – PSYCAVI Project | University of Rwanda
IT Specialist at FUZU – Kigali | Apply now
Important notice
⚠️ All Jobs and Opportunities published on fdo.net.rw are completely free to apply.
Never pay any fee during the recruitment process!
Even if fdo.net.rw does its best to avoid scam job or opportunity offers, job seekers or opportunity seekers are 100% responsible for applying at their own risk.
Check carefully before applying. If you doubt the legitimacy of any offer, do not apply and contact us at
freedigopp54@gmail.com
Never pay to get a job or opportunity - if you do, you do so at your own risk.
