dynamic memory allocation

22
1 | Page Topic:- DYNAMIC MEMORY ALLOCATION

Upload: diwaker

Post on 18-Nov-2014

17 views

Category:

Documents


0 download

DESCRIPTION

this is all about basics of dynamic memory allocation and how it is done in c and c++by functions such as calloc, malloc, new, delete,free,realloc

TRANSCRIPT

Page 1: Dynamic Memory Allocation

1 | P a g e

Topic:- DYNAMIC MEMORY ALLOCATION

Page 2: Dynamic Memory Allocation

2 | P a g e

TABLE OF CONTENTS

S.No. Topic Page No.

1. Acknowledgement 2

2. Introduction 4

3. Topic Introduction 5

4. Types of Memory Allocation 5-6

5. How does dynamic memory allocation work

6-8

6. Dynamic Memory Allocation using C programming Language

8-13

7. Dynamic Memory Allocation using C++ programming Language

13-15

8. Advantages of Dynamic Memory Allocation

16

9. Disadvantages of Dynamic Memory Allocation

16

10. References 18

Page 3: Dynamic Memory Allocation

3 | P a g e

INTRODUCTION

As it is clear from the name of the topic, the topic deals with the functions associated with dynamic memory allocation. This is my attempt to provide all the information as a zest or summary. I have tried to explain each and every term associated with dynamic memory allocation as far as possible. I hope that the reader will be able to know the fundamentals of dynamic memory allocation after reading this document.

Page 4: Dynamic Memory Allocation

4 | P a g e

1. TOPIC INTRODUCTION:

After listening the word “Dynamic Memory Allocation” the first thing which strikes our mind is “Memory Allocation”. What is memory allocation???

The answer to this is

The term “Memory Allocation” refers to the process of reserving memory for the variables and functions used in a program i.e. whenever we run a program , first memory is reserved for it either statically or dynamically which is utilised by the program variables and functions.

2. TYPES OF MEMORY ALLOCATION:

“Memory allocation” can be broadly classified into two categories:-

(a). STATIC MEMORY ALLOCATION

(b). DYNAMIC MEMORY ALLOCATION

(a) STATIC MEMORY ALLOCATION: - Static memory allocation means that memory for program is reserved at the compile time i.e. when the program is compiled. It would become more clear from the following program written in C:-

#include <stdlib.h>#include <stdio.h>#include <conio.h>#include <alloc.h>void main(){

clrscr()

int arr[5],i; Here memory for arr[5]and i is allocated statically i. e. at compile time.

for(i=0;i<5;i++){

printf(“\n Enter the number”);scanf(“%d”,&arr[i]);

}

printf(“Content of array is\n”);for(i=0;i<5;i++)

{

Page 5: Dynamic Memory Allocation

5 | P a g e

scanf(“%d\t”,&arr[i]);}

getch();}

(b) DYNAMIC MEMORY ALLOCATION:-Dynamic Memory Allocation is the allocation of memory storage for use in a computer program during the runtime of that program i.e. instead of allocating memory at compile time, the memory for variables and functions used in program is allocated at runtime. Following C program makes it more clear:-

#include <stdlib.h>#include <stdio.h>#include <conio.h>#include <alloc.h>

Void main(){

char *line;int linelen = 100;

line = malloc(linelen); Here 100 bytes are allocated at run timeprintf(“\n ENTER A LINE”)

getline(line, linelen);getch();

}

3: HOW DOES DYNAMIC MEMORY ALLOCATION WORK??

The key idea is to regard all the available memory as a large global pool that can be used for any purpose whatsoever. When you need memory, you ask for just the amount you need; it is given to you from the global pool and is marked as being no longer `free' so that a subsequent request for memory does not allocate this same block again for a different purpose. Memory allocation is done by some sort of procedure call; in C, malloc(n) allocates a block of memory of size n bytes.

It is your responsibility to return memory to the global pool when you are finished with it; when you do so it will be marked `free' again and be available for other uses (you might get it again the next time you request some memory).

To continue, we imagine that all the available memory is one large array to be used as a global pool:

Page 6: Dynamic Memory Allocation

6 | P a g e

We use gray shading to indicate the regions of memory that belong to the global pool, i.e. which are free. At present, all of it is free.

Now, if the user needs memory to store the name JOE, he must requests enough space to store the string "JOE". As it happens, in C, all strings must be terminated by a special character called `NULL' whose code is 0 and which is written \0. Therefore, the user needs 3 bytes to store J, O, and E, plus an additional byte for NULL. Thus he requests 4 bytes by calling malloc(4).

Suppose he is given the first 4 bytes from the pool; then memory would now look like this:

The memory allocator keeps track of what memory is free and what memory has been allocated. It now knows that the 4 bytes which it gave to the user are no longer free; they are no longer in the global pool. This we represent visually by the fact that these bytes are no longer shaded gray.

The question marks now visible indicate that we do not know in what state the bits of this block of memory really are.

A memory allocator typically makes no guarantee about this issue. The block of memory which is allocated and returned to the user must be presumed to contain garbage. It is the responsibility of the user to then initialize this block properly so that its contents become meaningful.

In the present case, the user simply copies the string "JOE" into it:

You can see that it takes up exactly the space that is needed for it. The rest of memory can be used to store the other names.

Suppose the next name is MARYJANE: 8 characters + 1 NULL. The user asks for 9 bytes and copies the string into them:

You may wonder why this new block is not contiguous with the previous one. The reason is that, in general, it won't be. This, mainly for two reasons:

Page 7: Dynamic Memory Allocation

7 | P a g e

The memory allocator might very well decide to allocate the next block from some other part of memory.

Often, the memory allocator needs to allocate a little bit more than the user requested so that it can store, just before the user's block, some information about it, such as its size. Thus, when the user wants to `free' the block, the memory allocator can find out how big it is and return the correct number of memory locations to the global pool.

For example, the real situation might look like this:

where the arrows point to the start of the blocks allocated to the user. In the following, we are going to ignore these details.

What to remember

The memory allocator keeps track of what is allocated and what is free. When we obtain memory from the global pool, we must assume that it contains

garbage, and properly initialize it. We must not assume that successive requests will allocate contiguous memory blocks.

If the user now says he is finished with the name JOE, the corresponding block of memory is returned to the global pool and becomes free:

4: DYNAMIC MEMORY ALLOCATION IN C PROGRAMMING LANGUAGE:-

In C programming language memory is allocated dynamically through the various functions provided in the C standard library. These functions include

(a). MALLOC ( )

(b). CALLOC ( )

(c). FREE ( )

(d). REALLOC ( )

Page 8: Dynamic Memory Allocation

8 | P a g e

(a). MALLOC( ) : The function malloc is used to allocate a certain amount of memory during the execution of a program. The malloc function will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory. When the amount of memory is not needed anymore, you must return it to the operating system by calling the function free. Main features of malloc() function have been described below

This function allocates the block of memory in bytes. This function is like a request to the RAM of the system to allocate the

memory, if the request is granted, it returns a pointer to the first block of that block of memory & the type of pointer it returns is void. And if the request is not granted then it returns a NULL.

This function is available in the header file <stdlib.h> or <alloc.h> Syntax of this function is :

malloc(number of elements*size of each element);

Example :int*ptr;ptr=malloc(10*sizeof(int));

Since type of pointer it returns is void, so typecasting is required to change the return pointer type.

Example of typecasting:int*ptr;ptr=(int*)malloc(10*sizeof(int));

Example program using malloc() function:-

#include<stdio.h>

int main(){

int *ptr_one;

ptr_one = (int *)malloc(sizeof(int));

if (ptr_one == 0){

printf("ERROR: Out of memory\n");return 1;

}

*ptr_one = 25;printf("%d\n", *ptr_one);

free(ptr_one);

Page 9: Dynamic Memory Allocation

9 | P a g e

return 0;}

(b).CALLOC( ) : The function calloc() will allocate a block of memory for an array. All of these elements are size bytes long. During the initialization all bits are set to zero. Main features of calloc() function are described below.

It works similar to the malloc() function except that it requires two argument.

Syntax for this function :ptr = calloc(number of elements, size of each element);

Example :int*ptr;ptr = (int*)calloc(10,2);

This function is available in the header file <stdlib.h> or <alloc.h> The memory allocated by the malloc() contains garbage values & the

memory allocated by calloc() contains all zeros.

Example program using calloc() function:-

#include<stdio.h>#include<stdlib.h>

int main (){

int a,n;int * ptr_data;

printf ("Enter amount: ");scanf ("%d",&a);

ptr_data = (int*) calloc ( a,sizeof(int) );if (ptr_data==NULL){

printf ("Error allocating requested memory");exit (1);

}

for ( n=0; n<a; n++ ){

printf ("Enter number #%d: ",n);scanf ("%d",&ptr_data[n]);

}

Page 10: Dynamic Memory Allocation

10 | P a g e

printf ("Output: ");for ( n=0; n<a; n++ )

printf ("%d ",ptr_data[n]);

free (ptr_data);return 0;

}

(c). FREE( ) : If you have allocated a memory block with the functions malloc(), calloc() or realloc() then you need to free the previously allocated memory. Its main features are:s

This function is used to de-allocate the previously allocated memory using malloc ( ) or calloc ( ) function.

Free function is used to return the allocated memory block to the system memory RAM.

Syntax for this function is:Free ( ptr );

Example program using free() function:-

#include<stdio.h>#include<stdlib.h>

int main (){

int * buffer;

/*get a initial memory block*/buffer = (int*) malloc (10*sizeof(int));

/*free initial memory block*/free (buffer);return 0;

}

(d). REALLOC( ) : The function realloc() reallocates a memory block with a specific new size. If you call realloc() the size of the memory block pointed to by the pointer is changed to

Page 11: Dynamic Memory Allocation

11 | P a g e

the given size in bytes. This way you are able to expand and reduce the amount of memory you want to use (if available of course.)

It is possible that the function moves the memory block to a new location, in which way the function will return this new location. If the size of the requested block is larger then the previous block then the value of the new portion is indeterminate.

If the pointer is NULL then the function will behave exactly like the function malloc(). It will assign a new block of a size in bytes and will return a pointer to it.

If the size is 0 then the memory that was previously allocated is freed as if a call of the function free() was given. It will return a NULL pointer in that case. Main features are:

This function is used to resize the size of memory block, which is already allocated.

This function is available in the header file < stdlib.h > or < alloc.h > Note that before using the realloc ( ) function, the memory block to be

resized should be allocated using the following statement:ptr = malloc (size);

Syntax of this function :

ptr = realloc (ptr, new_size);

Example program using realloc() function:-

#include<stdio.h>#include<stdlib.h>

int main (){

int * buffer;

/*get a initial memory block*/buffer = (int*) malloc (10*sizeof(int));if (buffer==NULL){

printf("Error allocating memory!");exit (1);

}

/*get more memory with realloc*/buffer = (int*) realloc (buffer, 20*sizeof(int));if (buffer==NULL){

printf("Error reallocating memory!");//Free the initial memory block.free (buffer);exit (1);

}free (buffer);

Page 12: Dynamic Memory Allocation

12 | P a g e

return 0;}

We can summarise the result as:-

Function

Task

malloc() Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space

calloc() Allocates space for an array of elements initializes them to zero and returns a pointer to the memory

free() Frees previously allocated space

realloc() Modifies the size of previously allocated space.

5: DYNAMIC MEMORY ALLOCATION IN C++ PROGRAMMING LANGUAGE:-

C++ provides two dynamic allocation operators: new and delete. These operators areused to allocate and free memory at run time. Dynamic allocation is an important part of almost all real-world programs. As explained in Part One, C++ also supports dynamic memory allocation functions, called malloc() and free(). These are included for the sake of compatibility with C. However, for C++ code, you should use the new and delete operators because they have several advantages. The new operator allocates memory and returns a pointer to the start of it. The delete operator frees memory previously allocated using new.

Page 13: Dynamic Memory Allocation

13 | P a g e

The general forms of new and delete are shown here:

p_var = new type;delete p_var

Here, p_var is a pointer variable that receives a pointer to memory that is large enough to hold an item of type type . Since the heap is finite, it can become exhausted. If there is nsufficient available memory to fill an allocation request, then new will fail and a bad_alloc exception will be generated. This exception is defined in the header <new>. Your program should handle this exception and take appropriate action if a failure occurs. If this exception is not handled by your program, then your program will be terminated.

The actions of new on failure as just described are specified by Standard C++. The trouble is that not all compilers, especially older ones, will have implemented new in compliance with Standard C++. When C++ was first invented, new returned null on failure. Later, this was changed such that new caused an exception on failure. Finally, it was decided that a new failure will generate an exception by default, but that a null pointer could be returned instead, as an option. Thus, new has been implemented differently, at different times, by compiler manufacturers. Although all compilers will eventually implement new in compliance with Standard C++, currently the only way to know the precise action of new on failure is to check your compiler's documentation. Since Standard C++ specifies that new generates an exception on failure, this is the way the code in this book is written. If your compiler handles an allocation failure differently, you will need to make the appropriate changes.

Here is a program that allocates memory to hold an integer:

#include <iostream>#include <new>using namespace std;int main(){int *p;try {

p = new int; // allocate space for an int} catch (bad_alloc xa) {cout << "Allocation Failure\n";return 1;}*p = 100;cout << "At " << p << " ";cout << "is the value " << *p << "\n";delete p;return 0;}

This program assigns to p an address in the heap that is large enough to hold an integer. It then assigns that memory the value 100 and displays the contents of the memory on the screen. Finally, it frees the dynamically allocated memory. Remember, if your compiler implements new such that it returns null on failure, you must change the preceding program appropriately.

Page 14: Dynamic Memory Allocation

14 | P a g e

The delete operator must be used only with a valid pointer previously allocated by using new. Using any other type of pointer with delete is undefined and will almost certainly cause serious problems, such as a system crash.

6: ADVANTAGES OF NEW AND DELETE OVER MALLOC() AND FREE()

Although new and delete perform functions similar to malloc() and free(), they have several advantages.1. Firstly, new automatically allocates enough memory to hold an object of the specified type. You do not need to use the sizeof operator. Because the size is computed automatically, it eliminates any possibility for error in this regard.

2. Secondly, new automatically returns a pointer of the specified type. You don't need to use an explicit type cast as you do when allocating memory by using malloc().

3.Finally, both new and delete can be overloaded, allowing you to create customized allocation systems. Although there is no formal rule that states this, it is best not to mix new and delete with malloc() and free() in the same program. There is no guarantee that they aremutually compatible.

Initializing Allocated MemoryYou can initialize allocated memory to some known value by putting an initializer afterthe type name in the new statement. Here is the general form of new when an initialization is included:

p_var = new var_type (initializer);

Of course, the type of the initializer must be compatible with the type of data for whichmemory is being allocated.This program gives the allocated integer an initial value of 87:

#include <iostream>#include <new>using namespace std;int main(){int *p;try {p = new int (87); // initialize to 87} catch (bad_alloc xa) {cout << "Allocation Failure\n";return 1;}cout << "At " << p << " ";cout << "is the value " << *p << "\n";delete p;return 0;}

Page 15: Dynamic Memory Allocation

15 | P a g e

7: ADVANTAGES OF DYNAMIC MEMORY ALLOCATION:

The main advantage of using dynamic memory allocation is preventing the wastage of memory. This is because when we use static memory allocation, a lot of memory is wasted because all the memory allocated cannot be utilised. Thus dynamic memory allocation helps us to allocate memory as and when required and thus saves memory.

8: DISADVANTAGES OF DYNAMIC MEMORY ALLOCATION:

Freeing Memory

The user is responsible for freeing up memory when he is finished with it. This is a serious responsibility, a potential source of bugs that are very hard to find.

For example, suppose you free up a location before you're actually finished with it. Then further access to the location will either cause a run-time error (memory violation) or, what is worse (but more common), you will get access to a location that is being used for some completely unrelated purpose.

Trouble also occurs if you forget to free up some space. If you do this, you are losing the advantages of dynamic allocation. And in some circumstances - e.g. if you were writing the program that manages the space on a disk drive - this could be disastrous.

There are no surefire safeguards against these problems, you must be very careful when writing programs to return memory when you are finished with it, but not before.

Fragmentation of Memory

As the preceding example demonstrated, with dynamic allocation the `free' parts of memory are not all together in one contiguous block. When we returned JOE's memory, we had 4 free cells on one side of MARYJANE and all the rest on the other side. This is called fragmentation of memory, and it can grow into a very serious problem: it is possible to have a large amount of free memory but for it to be broken up into such tiny fragments that there is not enough contiguous free space to store another name.

Suppose that after using dynamic allocation for a while memory becomes fragmented thus:

and that we need to obtain a block this big:

If only the remaining free blocks were contiguous, we'd have enough room, but, in the present configuration, it looks like we are doomed. There are several possible solutions to this problem. The one we will study is based on the insight that a large data structure does not

Page 16: Dynamic Memory Allocation

16 | P a g e

necessarily have to be allocated in one single contiguous chunk of memory. Instead it might be decomposed into smaller components that are somehow linked together in a chain.

Page 17: Dynamic Memory Allocation

17 | P a g e

REFERENCES

Sites:-

http://books.google.co.in

http://wikipaedia.com

http://wiki.answers.com

Books:-

C++ Complete Reference by Herbert Schildt

Let us C by Yashwant Kanitkar

ANSI C by Balagurusamy