0% found this document useful (0 votes)
12 views18 pages

CSE109 Week8.2

Uploaded by

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

CSE109 Week8.2

Uploaded by

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

Dynamic Memory Allocation

Lecture: 19
Reference Book: Teach yourself C (3rd Ed.)
Chapter/Section: A.4

Samin Rahman Khan


Lecturer (part-time), CSE, BUET
Lecturer, IICT, BUET
Dynamic Allocation
● Primary ways to store information in C - Global and local
variables.
○ In case of global and static local variables, the storage is fixed
throughout the runtime of the program.
○ For dynamic local variables, memory is allocated on the stack.
Although these variables are efficiently implemented in C, they
require the programmer to know in advance the amount of
storage needed for every situation.
● The second way is C’s dynamic allocation system. In this method,
storage for information is allocated from the free memory area
(called the heap) as it is needed.
Memoy Layout
Dynamic Allocation
● The ANSI C standard specifies that the header information
necessary to the dynamic allocation system is in STDLIB.H.
● In this file, the type size_t is defined. This type is used extensively
by allocation functions.
Malloc

#include <stdlib.h>
void *malloc(size_t size);

● The malloc( ) function returns a pointer to the first byte of a


region of memory of size size that has been allocated from the
heap.
● If there is insufficient memory in the heap to satisfy the
request, malloc( ) returns a null pointer.
● It is important to verify that the return value is not a null
pointer before attempting to use it. Attempting to use a null
pointer will usually result in a system crash.
Free

#include <stdlib.h>
void free(void *ptr);

● The free( ) function deallocates the memory pointed to by ptr.


This makes the memory available for future allocation.
● It is imperative that the free( ) function be called only with a
pointer that was previously allocated using one of the
dynamic allocation system’s functions, such as malloc( ) or
calloc( ).
● Using an invalid pointer in the call will probably destroy the
memory management mechanism and crash the sytem.
Example
#include <stdio.h>
#include <stdlib.h>

int main(void) {

char *str[100];
for (int i = 0; i < 100; ++i) {
if ((str[i] = malloc(128)) == NULL) {
printf("Allocation error - aborting.\n");
exit(0);
}
gets(str[i]);
}

/* now free the memory */


for (int i = 0; i < 100; ++i) free(str[i]);
}
Using malloc to Allocate Storage for an Array
int *a;

a = malloc(n * sizeof(int));

for (int i = 0; i < n; i++)


a[i] = 0;
Example
#include <stdio.h>
#include <stdlib.h> for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
printf("%d ", *(*(mat + i) + j));
int main(void) {
}
int col, row; printf("\n");
scanf("%d %d", &col, &row); }
}

int **mat = malloc(row * sizeof(int*));

for (int i = 0; i < row; ++i) {


*(mat + i) = malloc(col * sizeof(int));
}

for (int i = 0; i < row; ++i) {


for (int j = 0; j < col; ++j) {
int num;
scanf("%d", &num);
*(*(mat + i) + j) = num;
}
Example
#include <stdio.h>
#include <stdlib.h> for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
printf("%d ", *(*(mat + i) + j));
int main(void) { }
int col, row; printf("\n");
scanf("%d %d", &col, &row); }
}

int **mat = malloc(row * sizeof(int*));

for (int i = 0; i < row; ++i) {


*(mat + i) = malloc(col *
sizeof(int));
}

for (int i = 0; i < row; ++i) {


for (int j = 0; j < col; ++j) {
scanf("%d", *(mat + i) + j);
}
}
Example
#include <stdio.h>
#include <stdlib.h> for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
printf("%d ", mat[i][j]);
int main(void) { }
int col, row; printf("\n");
}
scanf("%d %d", &col, &row);
}

int **mat = malloc(row * sizeof(int*));

for (int i = 0; i < row; ++i) {


mat[i] = malloc(col * sizeof(int));
}

for (int i = 0; i < row; ++i) {


for (int j = 0; j < col; ++j) {
int num;
scanf("%d", &num);
mat[i][j] = num;
}
Example
#include <stdio.h>
for (int i = 0; i < row; ++i) {
#include <stdlib.h>
for (int j = 0; j < col; ++j) {
int num;
int main(void) { scanf("%d", &num);
int col, row; mat[i][j] = num;
scanf("%d %d", &col, &row); }
}
int **mat = malloc(row * sizeof(int*));
if (mat == NULL) { for (int i = 0; i < row; ++i) {
printf("Could not allocate memory."); for (int j = 0; j < col; ++j) {
exit(0); printf("%d ", mat[i][j]);

} }
printf("\n");
}
for (int i = 0; i < row; ++i) {
mat[i] = malloc(col * sizeof(int));
for (int i = 0; i < row; ++i) free(mat[i]);
if (mat[i] == NULL) {
free(mat);
printf("Could not allocate
}
memory.");
exit(0);
}
Recap: Pointer to struct
typedef struct point {
float x;
Point* midPoint(Point* point1, Point*
float y; point2)
} Point; {
Point* result = malloc(sizeof(Point));
Point* midPoint(Point* point1, Point* result->x = (point1->x+point2->x)/2;
point2); result->y = (point1->y+point2->y)/2;
return result;
int main(void) }
{
Point P, Q, *M;
scanf("%f %f",&P.x,&P.y);
scanf("%f %f",&Q.x,&Q.y);
M = midPoint(&P,&Q);
printf("%f %f",M->x,M->y);
return 0;
}
Using malloc to Allocate Storage for a struct
typedef struct point {
float x;
Point midPoint(Point* point1, Point* point2)
float y;
{
} Point;
Point result;
result.x = (point1->x+point2->x)/2;
Point midPoint(Point* point1, Point* point2); result.y = (point1->y+point2->y)/2;
return result;
int main(void) }
{
Point P, Q, M;
scanf("%f %f",&P.x,&P.y);
scanf("%f %f",&Q.x,&Q.y);
M = midPoint(&P,&Q);
printf("%f %f",M.x,M.y);
free(M);
return 0;
}
Calloc

#include <stdlib.h>
void *calloc(size_t num, size_t size);

● The calloc( ) function returns a pointer to the first byte of a


region of memory of size num * size that has been allocated
from the heap.
● If there is insufficient memory in the heap to satisfy the
request, calloc( ) returns a null pointer.
● It is important to verify that the return value is not a null
pointer before attempting to use it. Attempting to use a null
pointer will usually result in a system crash.
● calloc( ) initializes every byte in the allocated memory to 0.
Realloc

#include <stdlib.h>
void *realloc(void *ptr, size_t size);

● The realloc( ) function changes the size of the allocated


memory pointer to by the ptr to that specified by size.
● The value of size may be greater or less than the original.
● A pointer to the memory block is returned since it may be
necessary for realloc( ) to move the block to increase its size.
If this occurs, the contents of the old block are copied into the
new block - no information is lost.
● If there is not enough free memory in the heap to allocate size
bytes, a null pointer is returned. This means it is important to
Example
#include <stdlib.h>
#include <stdio.h> p = realloc(p, 18);
#include <string.h> if (!p) {
printf("Allocation error -
int main() { aborting.\n");
char *p; exit(1);
p = malloc(17); }
if (!p) { strcat(p, ".");
printf("Allocation error -
aborting.\n"); printf(p);
exit(1);
} free(p);
strcpy(p, "this is 16 chars"); }
Example
#include <stdio.h>

int main() {
0x1f772a0
(nil)
int *p = malloc(0);
printf("%p\n", p);

int *q = malloc(-1);
printf("%p\n", q);

return 0;
}

You might also like