The document discusses dynamic memory allocation in C, highlighting the importance of memory management, the use of pointers, and the differences between static and dynamic memory allocation. It details functions such as malloc(), calloc(), realloc(), and free(), which are essential for managing memory during program execution. Additionally, the document explains the concepts of stack and heap memory segments and provides examples of how to use these functions effectively.
Introduction
2
Memory managementis one of the most fundamental and important aspect for
any computer programming language.
In many programming language you don’t have to worry about the memory
management, but in C Programming Language you to do memory management
manually.
C is one of the most powerful programming language. Pointer is one of the most
powerful feature of the C programming language which gives you the ability to
point memory locations. This feature enables you easy memory access.
As we all know computer memory is made up of large number of cells. So it is
always necessary to manage these memory locations effectively to increase the
utilization.
To allocate memory it is necessary to keep information available memory in the
system. If memory management system finds sufficient free memory, it allocates
only as much memory as needed, keeping the rest available to satisfy future
request.
3.
Static or Compiletime memory allocation
3
In this method desired memory is allocated at the time of variable declaration or
beginning of the program.
Amount of memory allocation is fixed and is determined at the time of program
compilation.
Example:
int a, b;
When the first statement int a, b; is compiled 4 consecutive bytes for each
variable a, b will be allocated.
Drawbacks:
If we declare more number of variables and we are using less number of
variables then the memory allocated for the unused variables will be wasted.
The unused memory cells are not made available to other applications. This
leads to inefficient use of memory.
Size for the data type or variable must be know before.
We can not change the size of variable at run time.
4.
Dynamic or Runtimememory allocation
4
In the dynamic memory allocation, the memory is allocated to a variable
or program at the run time.
The only way to access this dynamically allocated memory is through
pointer.
It makes efficient use of memory.
C provides the following dynamic allocation and de-allocation functions –
1. malloc()
2. calloc()
3. realloc()
4. free()
These library routines known as memory management functions are
used for allocating and freeing memory during execution of a program.
These functions are defined in stdlib.h header file.
malloc, calloc and realloc is used for memory allocation and de-
allocation is achieved by the use of free function.
5.
Stack and Heap
5
When program is loaded into main memory is divided into 4
segments: Code, Data, Stack, Heap
A Data segment contains the global and static variables.
A Code segment contains the executable instructions.
A Stack segment stores all auto variables/local variables.
Also each function call involves passing arguments from the
caller to callee. The callee may also declare variables.
Function parameters, return address and automatic local
variables are accommodated in a stack.
Hence a stack is an area of memory for storing data
temporarily.
Allocation and de-allocation of memory in this area is done
automatically.
6.
Stack and Heap…
6
Heap segment is for dynamic memory management.
It is for the programmers to manage.
We can allocate and deallocate memory when you feel the
need for it and delete when you feel that the memory is no
longer needed.
C language supports a pair functions named malloc() and free()
to allocate and deallocate memory/space from heap
respectively.
7.
malloc() function
7
Themalloc( ) function stands for memory allocation.
The malloc() function allocates the memory at run time whenever
required.
It allocates the memory of requested size and returns the pointer to the
first byte (base address) of allocated space or returns NULL if memory is
not sufficient ( failed to allocate).
The pointer returned is usually of type void. It means that we can assign
malloc() function to any pointer.
It doesn't initialize memory at execution time, so it has garbage value
initially.
Syntax:
8.
malloc( ) function…
8
Let us understand the malloc() with the following code :
ptr = malloc(8); // allocates 8 bytes of memory
Here ptr is a pointer variable and it allocates 8 bytes of memory. Here we have not defined
datatype of the variable and ptr is a void pointer now. It will now point to the first byte in
the allocated memory.
If we need to make this pointer as integer then we need specify the type also while
allocating memory then each integer value will be stored at the interval of 4 bytes.
ptr = (int*)malloc(8); //returns integer pointer to ptr pointing to first byte of allocated
memory
ptr = (int*)malloc(10* sizeof(int));
//allocates memory sufficient for 10 integer values and returns integer pointer to ptr
9.
malloc( ) function…
9
Let us understand the malloc( ) function with the following example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr;
ptr = (int *)malloc(10 * sizeof(int)); /* a block of 15 integers */
if (ptr == NULL)
printf("Error: Out of memoryn");
else
{
*(ptr + 5) = 480; /* assign 480 to sixth integer */
printf("Value of the 6th integer is %d",*(ptr + 5));
}
free(ptr);
return 0;
}
10.
free() function
10
Thefree( ) function is used to release the memory allocated by using
malloc ( ) or calloc () function.
It is always important to release the memory that is not in use, so it can be
used in future otherwise leads to memory leak.
If you don’t free it, your program grows larger and eventually runs out of
memory!
Syntax:
free (pointer_var_name);
Example:
free (ptr);
11.
calloc( ) function
11
The calloc( ) function stands for contiguous allocation.
The calloc() function is same malloc() except it is used to allocate multiple
blocks of memory and all blocks are initialized to zero.
It is used to allocate the memory to complex data structures such as arrays and
structures.
Syntax:
ptr = (cast-type *) calloc(n, size_in_bytes);
The above statement is used to allocate n memory blocks of the same size.
After the memory space is allocated, then all the bytes are initialized to zero.
The pointer which is currently at the first byte of the allocated memory space is
returned.
Example:
ptr = (int *) calloc(10, sizeof(int)); It allocates 10 memory blocks for storing 10
integers.
12.
realloc( ) function
12
realloc( ) stands for reallocation of memory.
Using the realloc( ) function, you can add more memory to already
allocated memory.
It expands the current block while leaving the original content as it is.
realloc() can also be used to reduce the size of the previously allocated
memory.
Syntax:
ptr = (cast-type *) realloc(ptr,new_size);
Example:
ptr = (char *) realloc(ptr, 20);
It allocates 20 new memory locations. We cannot be sure that if the newly
allocated block will point to the same location as that of the previous
13.
realloc( ) function…
13
Let us understand the realloc( ) function with the following example:
int main ( )
{
char *ptr;
ptr = (char *) malloc(10); //allocated 10 bytes of memory
strcpy(ptr, "Programming"); //copy the string to ptr
printf(" %s, Address = %un", ptr, ptr);
ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size 20
strcat(ptr, " In 'C' "); //concatenation
printf(" %s, Address = %un", ptr, ptr);
free(ptr);
return 0;
}
14.
Array of pointers
14
“Array of pointers” is an array of the pointer variables. It is also known as
pointer arrays.
Suppose we need to create an array of floating numbers to store 100
elements. Then:
float *ptr[100]; //creates 100 float pointer variables.
Another way to create dynamic array to store 100 float numbers
float *ptr;
ptr = (float *) malloc (100 * sizeof (float) ); //using malloc()
ptr = (float *) calloc (100, sizeof ( float ) ); //using calloc()
15.
15
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr;
printf("Enternumber of elements: ");
scanf("%d",&n);
//memory allocated using calloc
ptr=(int*)malloc(n*sizeof(int));
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("nAddress are:n");
for(i=0;i<n;++i)
{
printf("Adress = %ut
Value=%dn",(ptr+i),*(ptr+i));
//sum+=*(ptr+i);
}
printf("nSum=%d",sum);
free(ptr);
return 0;
}
Questions?
17
1. WAP tofind the largest number in an array using pointers?
2. WAP to sort the strings in alphabetical order using pointers
3. WAP to copy one string to another using pointers
4. WAP to reverse an array using pointers?
5. WAP to count the numbers of vowels in an array of characters
using pointers?
6. WAP to search an element in an array of "N" elements using
pointers?