CSE161 Lec 16 Dynamic Memory Allocation
CSE161 Lec 16 Dynamic Memory Allocation
ALLOCATION
Lecture: 16
Reference: Chapter 12.7 (Teach Yourself C)
1
Instructor:
Sushmit Hossain
Lecturer
Department of EEE
Brac University
INTRODUCTION
▪ Static memory allocation:
▪ Size of the memory that may be required for the program, should
be declared before loading and executing the code
▪ Example- Array declaration
2
PROBLEM WITH ARRAYS
▪ Sometimes
▪ Amount of data cannot be predicted beforehand
▪ Number of data items might change during program execution
3
BETTER SOLUTION
▪ Dynamic memory allocation
▪ Know how much memory is needed after the program is run
▪ Example: ask the user to enter the value of N from keyboard
▪ Dynamically allocate only the amount of memory needed
4
MEMORY MANAGEMENT
▪ Heap-allocated memory
▪ This is used for persistent data, that must survive beyond
the lifetime of a function call
▪ dynamically allocated memory – C statements can create new
heap data
▪ Like stack-allocated memory, the underlying system
determines where to get more memory – the programmer
doesn’t have to search for free memory space!
▪ Can be regarded as free memory
▪ Can only be accessed by pointers
6
MEMORY MANAGEMENT
▪ Heap-allocated memory
▪ This is used for persistent data, that must survive beyond
the lifetime of a function call
▪ dynamically allocated memory – C statements can create new
heap data
▪ Like stack-allocated memory, the underlying system
determines where to get more memory – the programmer
doesn’t have to search for free memory space!
▪ Can be regarded as free memory
▪ Can only be accessed by pointers
6
MEMORY ALLOCATION
FUNCTIONS
▪malloc()
▪ Allocates requested number of bytes and returns a pointer to
the first byte of the allocated space
▪ calloc()
▪ Allocates space for an array of elements, initializes them to
zero and then returns a pointer to the memory.
▪ realloc()
▪ Modifies the size of previously allocated space.
▪ free()
▪ Frees previously allocated space.
7
ALLOCATING A BLOCK OF
MEMORY
▪ A block of memory can be allocated in heap using the function malloc()
▪ Reserves a block of memory of specified size and returns a pointer of type void
▪ The return pointer can be type-casted to any pointer type
▪ General format:
type *p; // the type can be int, float, char etc
p = (type *) malloc (byte_size); // The pointer must be type-casted before use
▪ Example:
int *p;
p = (int *) malloc(100 * sizeof(int));
▪ A memory space equivalent to 100 times the size of an int bytes is reserved
▪ The address of the first byte of the allocated memory is assigned to the pointer p of type
int
p
in stack
400 bytes of space in heap
POINTS TO NOTE
▪ malloc always allocates a block of contiguous bytes
▪ The allocation can fail if sufficient contiguous memory space is not available
▪ If it fails, malloc returns NULL
▪ General syntax:
free (ptr);
▪ where ptr is a pointer to a memory block which has been previously
created using malloc
▪ Note that no size needs to be mentioned for the allocated block, the
system remembers it for each pointer returned
EXAMPLE-1.1
//input a string in a dynamically allocated memory
#include<stdio.h>
#include<stdlib.h>
#define SIZE 10
int main()
{
char *p;
p=(char*)malloc(SIZE);
if(p)
{
scanf("%s", p);
printf(p);
}
free(p);
return 0;
}
13
EXAMPLE-1.2
//input a string in a dynamically allocated memory
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *p;
int n;
scanf("%d", &n); // allocates memory according to the input from the user
p=(char*)malloc(n);
if(p)
{
scanf("%s", p);
printf(p);
}
free(p);
return 0;
}
14
EXAMPLE-2
//input an array of n elements in a dynamically allocated memory
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p, i, n;
scanf("%d", &n);
p=(int*)malloc(n*sizeof(int));
if(p)
{
for(i=0; i<n; i++)
{
scanf("%d", &p[i]);
printf("p %d is %d\n", i, p[i]);
}
}
free(p);
return 0;
}
15
EXAMPLE-3
// Stores the heights of n students in a dynamically allocated memory and calculates the average height
#include<stdio.h>
#include<stdlib.h>
int main(){
int i,N;
float *height;
float sum=0,avg;
for(i=0;i<N;i++)
sum += height[i];
1. Write a program that converts a numerical string to an integer. For example- if your input
string is “124”, the converted integer will be 124. [Use pointers]
1. Write a program to replace all the vowels with empty spaces in a sentence. For example-
if your input string is “Hello World!!”, your output string should be “H ll W rld!!” [The
sentence should be stored in a dynamically allocated memory. ] [CO3]
1. Write a program to count the number of occurrences of any two vowels in succession in a
line of text. For example, in the sentence “Please read this application and give me gratuity”
such occurrences are ea, ea,io,ui. So the output should be 4. [The line of text should be
stored in a dynamically allocated memory. ] [CO3]
17