0% found this document useful (0 votes)
66 views17 pages

CSE161 Lec 16 Dynamic Memory Allocation

The document discusses dynamic memory allocation in C. It explains that dynamic allocation allows memory to be allocated at runtime, as opposed to static allocation which requires declaring sizes at compile time. The malloc function allocates memory from the heap and returns a void pointer that must be typecast. Realloc can modify previously allocated blocks, and free returns memory to the system. Examples demonstrate dynamically allocating arrays, single variables, and releasing memory.

Uploaded by

Manus Human
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views17 pages

CSE161 Lec 16 Dynamic Memory Allocation

The document discusses dynamic memory allocation in C. It explains that dynamic allocation allows memory to be allocated at runtime, as opposed to static allocation which requires declaring sizes at compile time. The malloc function allocates memory from the heap and returns a void pointer that must be typecast. Realloc can modify previously allocated blocks, and free returns memory to the system. Examples demonstrate dynamically allocating arrays, single variables, and releasing memory.

Uploaded by

Manus Human
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

DYNAMIC MEMORY

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

▪ Dynamic memory allocation:


▪ Memory allocated at the run time
▪ Only pointers can access dynamically allocated memory
▪ Example- Use of malloc() function from stdlib.h

2
PROBLEM WITH ARRAYS
▪ Sometimes
▪ Amount of data cannot be predicted beforehand
▪ Number of data items might change during program execution

▪ Example: Search for an element in an array of N elements


▪ One solution: find the maximum possible value of N and allocate an array
of N elements
▪ Wasteful of memory space, as N may be much smaller in some
executions
▪ Example: maximum value of N may be 10,000, but a particular run may
need to search only among 100 elements
▪ Using array of size 10,000 always wastes memory in most cases

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

▪ C provides functions to dynamically allocate memory


▪ malloc, calloc, realloc

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

if ((p = (int *) malloc(100 * sizeof(int))) == NULL)


{
printf (“\n Memory cannot be allocated”);
exit();
}
USING THE MALLOC’D
ARRAY
Once the memory is allocated, it can be used with pointers, or with

array notation
▪ Example:
int *p, n, i;
scanf(“%d”, &n);
p = (int *) malloc (n * sizeof(int));
for (i=0; i<n; ++i)
scanf(“%d”, &p[i]);

The n integers allocated can be accessed as *p, *(p+1), *(p+2),…,


*(p+n-1) or just as p[0], p[1], p[2], …,p[n-1]
CAN WE ALLOCATE ONLY
ARRAYS?
▪ malloc can be used to allocate memory for single variables
also
▪ p = (int *) malloc (sizeof(int));
▪ Allocates space for a single int, which can be accessed as *p

▪ Single variable allocations are just special case of array


allocations
▪ Array with only one element
RELEASING THE ALLOCATED
SPACE: FREE
▪ An allocated block can be returned to the system for future use by
using the free function

▪ 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;

printf("Input no. of students\n");


scanf("%d", &N);

height = (float *) malloc(N * sizeof(float));


printf("Input heights for %d students \n",N);
for (i=0; i<N; i++)
scanf ("%f", &height[i]);

for(i=0;i<N;i++)
sum += height[i];

avg = sum / (float) N;


printf("Average height = %f \n",avg);
free (height);
return 0;
}
16
ASSIGNMENT-5 (LEC-15,16)
1. Write a program that converts all lowercase characters in a given string to its equivalent
uppercase character. [Use pointers]

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

You might also like