0% found this document useful (0 votes)
13 views

Memory Management

Uploaded by

bhasker
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Memory Management

Uploaded by

bhasker
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Dynamic MEMORY

MANAGEMENT
Allocating memory
There are two ways that memory gets allocated for data storage:
• Compile Time (or static) Allocation
– Memory for named variables is allocated by the compiler
– Exact size and type of storage must be known at compile time
– For standard array declarations, this is why the size has to be constant
• Dynamic Memory Allocation
– Memory allocated "on the fly" during run time
– dynamically allocated space usually placed in a program segment known as the heap or the
free store
– Exact amount of space or number of items does not have to be known by the compiler in
advance.
– For dynamic memory allocation, pointers are crucial
Memory allocation
• Memory in your C++ program is divided into two parts −
• The stack − All variables declared inside the function will take up
memory from the stack.
• The heap − This is unused memory of the program and can be
used to allocate the memory dynamically when program runs.
• Many times, you are not aware in advance how much memory
you will need to store particular information in a defined
variable and the size of required memory can be determined at
run time.
Dynamic Memory allocation
• You can allocate memory at run time within the heap for the
variable of a given type using a special operator in C++ which
returns the address of the space allocated. This operator is
called new operator.

• If you are not in need of dynamically allocated memory


anymore, you can use delete operator, which de-allocates
memory that was previously allocated by new operator.
New operator

• The new operator in C++ is used for dynamic storage allocation.


This operator can be used to create object of any type.
• The general syntax of new operator in C++ is as follows:

pointer variable = new datatype;

In the above statement, new is a keyword and the pointer


variable is a variable of type datatype.
Delete operator
• The delete operator in C++ is used for releasing memory space when the
object is no longer needed. Once a new operator is used, it is efficient to
use the corresponding delete operator for release of memory.
• The general syntax of delete operator in C++ is as follows:

delete pointer_variable;

In the above example, delete is a keyword and the pointer_variable is the


pointer that points to the objects already created in the new operator.
Allocating space with new
To allocate space dynamically, use the unary operator new, followed by the type being allocated.
new int; // dynamically allocates an int
new double; // dynamically allocates a double

If creating an array dynamically, use the same form, but put brackets with a size after the type:
new int[40]; // dynamically allocates an array of 40 ints
new double[size]; // dynamically allocates an array of size doubles
// note that the size can be a variable

These statements above are not very useful by themselves, because the allocated spaces have no names!
BUT, the new operator returns the starting address of the allocated space, and this address can be stored
in a pointer:
int * p; // declare a pointer p
p = new int; // dynamically allocate an int and load address into p

double * d; // declare a pointer d


d = new double; // dynamically allocate a double and load address into d
Accessing dynamically created space
For single items, we go through the pointer. Dereference the pointer to reach the
dynamically created target:
int * p = new int; // dynamic integer, pointed to by p

*p = 10; // assigns 10 to the dynamic integer


cout << *p; // prints 10
Deallocation of dynamic memory
To deallocate memory that was created with new, we use the unary operator delete.
The one operand should be a pointer that stores the address of the space to be
deallocated:
int * ptr = new int; // dynamically created int
// ...
delete ptr; // deletes the space that ptr points to

int * list = new int[40]; // dynamic array

delete [] list; // deallocates the array


EXAMPLE
#include <iostream>
#include <string.h> //for strlen
using namespace std;
int main()
{
char* str = "Idle hands are the devil's workshop.";
int len = strlen(str); //get length of str

char* ptr; //make a pointer to char


ptr = new char[len+1]; //set aside memory: string + '\0'
strcpy(ptr, str); //copy str to new memory area ptr
cout << "ptr=" << ptr << endl; //show that ptr is now in str
delete[] ptr; //release ptr's memory
return 0;
}
EXAMPLE
#include <iostream> cout << "Deleting str\n";
#include <string.h> //for strcpy(), etc delete[] str; //release memory
using namespace std; }
void display() //display the String
class String //user-defined string type
{
{ cout << str << endl;
private: }
char* str; //pointer to string };
public: int main()
String(char* s) //constructor, one arg { //uses 1-arg constructor
String s1 = "Who knows nothing doubts nothing.";
{
cout << "s1="; //display string
int length = strlen(s); //length of string s1.display();
argument getch();
str = new char[length+1]; //get memory return 0;
strcpy(str, s); //copy argument to it }
}
~String() //destructor
{
Self-referential class
• It is a special type of class. It is basically created for linked list
and tree based implementation in C++. If a class contains the
data member as pointer to object of similar class, then it is
called a self-referential class.
#include <iostream> int main()
using namespace std; {
class linked_list linked_list x, y, z;
{ x.next = &y;
public: y.next = &z;
linked_list() : next(nullptr), x(0) {} print(&x);
linked_list * next; return 0;
int x; }
};
void print(linked_list * b) {
if(b == nullptr)
return;
do {
cout << b->x << endl;
} while((b = b->next));
Memory Leaks
Memory leak description: Memory is allocated but not released
causing an application to consume memory reducing the available
memory for other applications.

• eventually causing the system to page virtual memory to the hard


drive slowing the application or crashing the application when than
the computer memory resource limits are reached. The system may
stop working as these limits are approached.
• A memory leak, occurs when a computer program acquires memory but fails to
release it back to the operating system. In object-oriented programming, a
memory leak may happen when an object is stored in memory but cannot be
accessed by the running code.A memory leak has symptoms similar to a
number of other problems (see below) and generally can only be diagnosed by
a programmer with access to the program source code.

• Because they can exhaust available system memory as an application runs,


memory leaks are often the cause of or a contributing factor to software aging.

• A memory leak can diminish the performance of the computer by reducing the
amount of available memory. Eventually, in the worst case, too much of the
available memory may become allocated and all or part of the system or device
stops working correctly, the application fails
An example of memory leak
• When a button is pressed: Get some memory, which will be
used to remember the floor number
• Put the floor number into the memory
• Are we already on the target floor?
• If so, we have nothing to do: finished Otherwise: Wait until the
lift is idle Go to the required floor
• Release the memory we used to remember the floor number
Allocation failure
• When an attempt is made to allocate to the heap but
insufficient memory is available, an allocation failure is
triggered. The output produced depends on the area of the
heap in which the allocation failure occurred.

You might also like