0% found this document useful (0 votes)
8 views23 pages

Dynamic Memory Allocation Lecture 21

The document discusses dynamic memory allocation in C programming. It covers the functions malloc(), calloc(), realloc() and free() for allocating, initializing, resizing and freeing memory dynamically at runtime. Examples are provided to demonstrate the usage of each function.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
8 views23 pages

Dynamic Memory Allocation Lecture 21

The document discusses dynamic memory allocation in C programming. It covers the functions malloc(), calloc(), realloc() and free() for allocating, initializing, resizing and freeing memory dynamically at runtime. Examples are provided to demonstrate the usage of each function.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 23

CSE101-Lec#21

• Dynamic memory management

©LPU CSE101 C Programming


Outline
• Dynamic Memory management
– malloc()
– calloc()
– realloc()
– free()

©LPU CSE101 C Programming


Dynamic Memory Allocation
• The statement:
int marks[100];
allocates block of memory to 100 elements of
type int and memory is also contiguous. If one
int requires 4 bytes of memory , a total of 400
bytes are allocated.
Why this approach of declaring array is not useful?
• This may lead to wastage of memory if all
allocated memory is not utilized.
©LPU CSE101 C Programming
• Dynamic memory allocation allows a program to obtain more
memory space, while running or to release space when no
space is required.
• So, it will allocate only that much of memory which is actually
required by the program.
• Hence memory wastage can be avoided/ or if more memory is
required that can also be allocated.
Function Use of Function
malloc() Allocates requested size of bytes and returns a pointer
first byte of allocated space
• There
calloc()are 4 library functions
Allocates space forunder "stdlib.h"
an array elements,for dynamic
initializes to
memory allocation.zero and then returns a pointer to memory
free() deallocate the previously allocated space
realloc() Change the size of previously allocated space

©LPU CSE101 C Programming


malloc()
• The name malloc stands for "memory allocation".
• The malloc() function allocates a block of memory of
specified size from the memory heap.
• Syntax:
void * malloc(size);
• Here size is the number of bytes of storage to be allocated.
• If memory is allocated successfully , it returns a pointer to
first location of newly allocated block of memory.
• If memory is not allocated i.e. no enough space exists for new
block or some other reason, returns NULL.

©LPU CSE101 C Programming


malloc()
• Return type of malloc() is void pointer , it has to be cast to the
type of data being dealt with.
• memory allocated by malloc() by default contain the garbage
values.
• Example:
int *p;
p=(int*)malloc(n*sizeof(int));
• In the above example, p is pointer of type integer
• int* tells to what type it will be pointing. int tells that the
malloc() function is type casted to return the address of
integer variable.
• n is the number of elements

©LPU CSE101 C Programming


Program example-malloc()
#include<stdio.h>
#include<stdlib.h>
int main( )
{
int *p,n,i;
printf ("Enter the number of integers to be entered ") ;
scanf("%d" ,&n) ;
p=(int*)malloc(n*sizeof(int));//malloc() returns void* so we need to typecast with the specific data type
if(p==NULL)
{
printf("Memory not available\n");
exit(1);
}
else
{
printf("\n Mmeory allocation was successful");
printf ("\nEnter integer values ") ;
for(i=0;i<n;i++)
{
scanf("%d",p+i);//In place of p+i we can write &p[i](treating it as ID array)
}
for(i=0;i<n;i++)
printf("\n%d",*(p+i));//In place of *(p+i) we can write p[i](treating it as ID array)
}
©LPUreturn
CSE101 0; C Programming
calloc()
•The name calloc stands for "contiguous allocation".
•It provides access to memory, which is available for dynamic
allocation of variable-sized blocks of memory.
•Syntax:
void *calloc(size_t nitems, size_t size);
•calloc is similar to malloc, but the main difference is that the values
stored in the allocated memory space is zero by default. With malloc,
the allocated memory could have any garbage value.
•calloc() requires two arguments.
1. The first is the number of variables you'd like to allocate
memory for.
2. The second is the size of each variable.

©LPU CSE101 C Programming


calloc()
• If memory is allocated successfully, function
calloc()returns a pointer to the first location of
newly allocated block of memory otherwise returns
NULL
• Memory allocated by calloc() by default
contains the zero values.
• E.g. If we want to allocate memory for storing n
integer numbers in contiguous memory locations
int *p;
p=(int*)calloc(n, sizeof(int));
©LPU CSE101 C Programming
Program example-calloc()
#include<stdio.h>
#include<stdlib.h>
int main( )
{

int *p,n,i;
printf("Enter the number of blocks we want to reserve:") ;
scanf("%d",&n) ;
p=(int*)calloc(n,sizeof(int));//malloc() returns void* so we need to typecast with the specific data type
if(p==NULL)
{
printf("Memory not available\n");
exit(1);
}
else
{
printf("\n Memory allocation successful");
printf ("\nEnter integer values: ") ;
for(i=0;i<n;i++)
{
scanf("%d",p+i);
}
printf("\n Entered values are:");
for(i=0;i<n;i++)
printf("\n%d",*(p+i));
return 0;
©LPU}CSE101 C Programming
Difference between malloc() and calloc()
calloc() malloc()
Function: Allocates a region of memory Allocates "size" bytes of
large enough to hold "n memory.
elements" of "size" bytes each.

Syntax: void *calloc void *malloc


(number_of_blocks, (size_in_bytes);
size_in_bytes);
No. of arguments: 2 1
Contents of The allocated region is initialized The contents of allocated
allocated memory: to zero. memory are not changed. i.e.,
the memory contains garbage
values.

Return value: void pointer (void *). void pointer (void *).
If the allocation succeeds, a If the allocation succeeds, a
pointer to the block of memory pointer to the block of memory
is returned. is returned.

©LPU CSE101 C Programming


realloc()
• Now suppose you've allocated a certain number of
bytes for an array but later find that you want to add
values to it. You could copy everything into a larger
array, which is inefficient, or you can allocate more
bytes using realloc(), without losing your data.
• realloc() takes two arguments.
1. The first is the pointer referencing the memory.
2. The second is the total number of bytes you want to
reallocate.
• Passing zero as the second argument is the equivalent
of calling free.
• Syntax:
void *realloc(pointerToObject, newsize);
©LPU CSE101 C Programming
realloc()
• If memory is allocated successfully, function
realloc()returns a pointer to the first
location of newly allocated block of memory
which may be at same site or at new site and
copy the contents from previous location to a
new location if required , otherwise returns
NULL.

©LPU CSE101 C Programming


Program example-realloc()
#include<stdio.h> • if(ptr==NULL)
#include<stdlib.h>
int main()
{
{ printf("\n Memory allocation failure while realloation");
int *ptr,n,m,i; exit(2);
printf("\n Enter initial value of n:");
scanf("%d",&n); }
ptr=(int *)calloc(n,sizeof(int)); else
if(ptr==NULL)
{
{
printf("\n Memory allocation failure(calloc())"); printf("\n Memory reallocated successfully");
exit(1); printf("\n Enter new values as per requirement");
}
else for(i=m;i<n;i++)
{ {
printf("\n Memory allocation successful");
scanf("%d",ptr+i);
printf("\n Enter values as per initial requirement:");
for(i=0;i<n;i++) }
{ printf("\n All values entered are(old+new):");
scanf("%d",ptr+i);
} for(i=0;i<n;i++)
printf("\n Entered values are:"); {
for(i=0;i<n;i++) printf("\n%d",*(ptr+i));
{
printf("\n%d",*(ptr+i)); }
} }
m=n;
printf("\n Enter new value of n for reallocation:");
free(ptr);
scanf("%d",&n); printf("\n Memory deallocated");
ptr=(int *)realloc(ptr,n*sizeof(int)); }
return 0;
}
©LPU CSE101 C Programming
free()
• Deallocates a memory block allocated by
previous call to malloc(), calloc() or
realloc() and return it to memory to be
used for other purposes.
• Syntax:
void free(void *ptr);
• The argument of function free() is the
pointer to block of memory which is to be
freed.
©LPU CSE101 C Programming
free()
• The realloc() function can behave the
same as free() function provided the
second argument passed to realloc() is 0.
free(ptr);
which is equivalent to
realloc(ptr,0);

©LPU CSE101 C Programming


#include<stdio.h>
Program example-free()
#include<stdlib.h>
int main( )
{
int *p,n,i;
printf ("Enter the number of integers to be entered ") ;
scanf("%d" ,&n) ;
p=(int*)malloc(n*sizeof(int));//malloc() returns void* so we need to typecast with the specific data type
if(p==NULL)
{
printf("Memory not available\n");
exit(1);
}
else
{
printf("\n Mmeory allocation was successful");
printf ("\nEnter integer values ") ;
for(i=0;i<n;i++)
{
scanf("%d",p+i);//In place of p+i we can write &p[i](treating it as ID array)
}
for(i=0;i<n;i++)
printf("\n%d",*(p+i));//In place of *(p+i) we can write p[i](treating it as ID array)
}
free(p);
©LPU CSE101 C Programming
Memory Leak
• A condition caused by a program that does not free
up the extra memory it allocates.
• It occurs when the dynamically allocated memory is
no longer needed but it is not freed.
• If we continuously keep on allocating the memory
without freeing it for reuse, the entire heap storage
will be exhausted.
• In such circumstances, the memory allocation
functions will start failing and program will start
behaving unexpectedly
©LPU CSE101 C Programming
Program example-Memory leak
#include<stdio.h>
int main()
{
int *p;
p=(int*)malloc(1*sizeof(int));
*p=6;
printf("%d",*p);
//Memory was not deallocated, hence memory leak may arise
//Solution
//free(ptr);
return 0;
}

©LPU CSE101 C Programming


Q1
What is the return type of malloc() or calloc()?
A. void *
B. Pointer of allocated memory type
C. void **
D. int *

©LPU CSE101 C Programming


Q2
What is the problem with following code?
#include<stdio.h>
int main()
{
int *p = (int *)malloc(sizeof(int));
p = NULL;
free(p);
}
A. Compiler Error: free can't be applied on NULL pointer
B. Memory Leak
C. Dangling Pointer
D. The program may crash as free() is called for NULL pointer.

©LPU CSE101 C Programming


Q3
The most appropriate matching for the following pairs
X: m=malloc(5); m= NULL; 1: using dangling pointers
Y: free(n); *n=5; 2: using uninitialized pointers
Z: int *p; *p = 10; 3. lost memory is:
A. X—1 Y—3 Z-2
B. X—2 Y—1 Z-3
C. X—3 Y—2 Z-1
D. X—3 Y—1 Z-2

©LPU CSE101 C Programming


Q4
realloc(ptr, size), where size is zero means
a. Allocate a memory location with zero length
b. Free the memory pointed to by ptr
c. Undefined behaviour
d. Doesn’t do any reallocation of ptr i.e. no
operation

©LPU CSE101 C Programming

You might also like