You are on page 1of 8

Dynamic Memory

Allocation
CSC-103 Programming Fundamentals
CSC-141 Introduction to Computer Programming

Lecture 20
Slides prepared by: Dr. Omar Ahmad
Lecture outline
• Memory allocation of variables and arrays in C
• Why do we need to change memory allocation at run time?
• Syntax and usage of memory allocation functions in C.
• malloc()
• calloc()
• free()
• realloc()
• Using DMA with structures
• Introduction to a dynamic array: The linked list

2
Structure Arrays
• Like other primitive types, array of struct employee
structures are also allowed in C.
{ int id;
• Here emp_list[5] is an array of
structures with 5 elements. char name[20];
float salary;
• Individual members of one of the
elements may be accessed using the };
dot operator. struct employee emp_list[5];

3
Memory Map of Structure Arrays

4
Accessing Elements in Structure Arrays
• Individual structure elements in an array follow the pattern
array_name[index].member_name
• Here emp_list[5] is an array of structures with 5 elements.
• Individual members of one of the elements may be accessed using the dot operator.

printf("Enter the employee ID: "); struct employee


scanf("%d", &emp_list[i].id); { int id;
getchar(); char name[20];
printf("Enter employee name: "); float salary;
fgets(emp_list[i].name, 20, stdin); };
printf("Enter salary: ");
struct employee emp_list[5];
scanf("%f", &emp_list[i].salary);
5
Pointers to Structures
• Like primitive types, we can have pointer to a structure.
• struct employee * ptr_emp = &emp1;
• Individual members of the structures may be accessed
using the arrow -> operator.

struct employee emp1;


struct employee
input_employee_data(emp1);
struct employee * ptr_emp; { int id;
ptr_emp = &emp1; char name[20];
printf("ID: %d\n", ptr_emp->id); float salary;
printf("Name: %s", ptr_emp->name);
};
printf("ID: %.3f\n", ptr_emp->salary);
6
References
• https://www.guru99.com/c-dynamic-memory-allocation.html
• https://www.javatpoint.com/dynamic-memory-allocation-in-c
• https://www.programiz.com/c-programming/c-dynamic-memory-all
ocation
• https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-us
ing-malloc-calloc-free-and-realloc/
• https://aticleworld.com/dangling-pointer-and-memory-leak/

7
Structure Padding in C
• In this case, when we calculate the size of the struct student, it
struct student
comes to be 6 bytes.
• But this answer is wrong. {
• 8 bytes are allocated when a variable of this type is declared. char a; // 1 byte
• This is due to a speed-up memory access feature of C.
• See the below link for details.
char b; // 1 byte
int c; // 4 bytes
};

https://www.javatpoint.com/structure-padding-in-c
8

You might also like