0% found this document useful (0 votes)
30 views65 pages

Chapter-2 DMA-1

The document discusses dynamic memory allocation in C programming, covering topics such as data types, pointers, arrays, and memory management functions like malloc and free. It explains the structure of C programs, the need for arrays, and the use of pointers for dynamic memory allocation and function handling. Additionally, it highlights the concept of call by reference and its advantages in modifying original variable values.

Uploaded by

jojac32799
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)
30 views65 pages

Chapter-2 DMA-1

The document discusses dynamic memory allocation in C programming, covering topics such as data types, pointers, arrays, and memory management functions like malloc and free. It explains the structure of C programs, the need for arrays, and the use of pointers for dynamic memory allocation and function handling. Additionally, it highlights the concept of call by reference and its advantages in modifying original variable values.

Uploaded by

jojac32799
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/ 65

Dynamic Memory Allocation

Chapter-1
Dr. Chintan Thacker, Associate Professor
AI_ML Department, PIET
Chapter- 1
DYNAMIC MEMORY ALLOCATION
CONTENT

● Revision of Data Type and Array


● Pointer
● Call By Reference
● malloc and calloc
● realloc and free
● Array of Pointers
● Programming Applications
● Dangling Pointer
Structure of C program
Structure of C program
Structure of C program
/*
Documentation section
C programming structure
*/
#include <stdio.h> /* Link section */
int subtract = 0; /* Global declaration, definition section */
int all (int, int); /* Function declaration section */
int main () /* Main function */
{ OUTPUT
printf("Welcome to PU tutorials!\n\n");
printf ("This is a C program \n");
subtract= all (25,10);
????????
printf ("Subtraction of the two numbers : %d \n", subtract);
return 0;
}
int all (int x, int y) /* User defined function */
{
return x-y; /* definition section */
}
Data Types
• Data types are defined as the data storage format that a variable can
store a data.
• It determines the type and size of data associated with variables.
Primary Data Type
• Primary data types are built in data types which are directly supported by machine.
• They are also known as fundamental data types.
int:
• int datatype can store integer number which is whole number without fraction part such as 10,
105 etc.
• C language has 3 classes of integer storage namely short int, int and long int.
• Example: int a=10;

float:
• float data type can store floating point number which represents a real number with decimal
point and fractional part such as 10.50, 155.25 etc.
• When the accuracy of the floating point number is insufficient, we can use the double to define
the number. The double is same as float but with longer precision.
• To extend the precision further we can use long double which consumes 80 bits of memory
space.
• Example: float a=10.50;
Primary Data Type
char:
• char data type can store single character of alphabet or digit or special symbol such as ‘a’, ‘5’
etc.
• Each character is assigned some integer value which is known as ASCII values.
• Example: char a=‘a’;

void:
• The void type has no value therefore we cannot declare it as variable as we did in case of int
or float or char.
• The void data type is used to indicate that function is not returning anything.
Secondary Data Type
• Secondary data types are not directly supported by the machine.
• It is combination of primary data types to handle real life data in more convenient way.
• It can be further divided in two categories:

Derived data types: Derived data type is extension of primary data type. It is built-in system and its
structure cannot be changed. Examples: Array and Pointer.
• Array: An array is a fixed-size sequenced collection of elements of the same data type.
• Pointer: Pointer is a special variable which contains memory address of another variable.

User defined data types: User defined data type can be created by programmer using combination
of primary data type and/or derived data type. Examples: Structure, Union, Enum.
• Structure: Structure is a collection of logically related data items of different data types grouped
together under a single name.
• Union: Union is like a structure, except that each element shares the common memory.
• Enum: Enum is used to assign names to integral constants, the names make a program easy to
read and maintain.
Need of Array Variable

 Suppose we need to store rollno of the student in the integer variable.


Declaration
int rollno;

 Now we need to store rollno of 100 students.


Declaration
int rollno101, rollno102, rollno103, rollno104...;

 This is not appropriate to declare these many integer variables.


e.g. 100 integer variables for rollno.

 Solution to declare and store multiple variables of similar type is an array.


 An array is a variable that can store multiple values.
Definition: Array

• An array is a fixed size sequential collection of elements of same data type grouped
under single variable name.
Declaring an array
Syntax
 By default array index starts with
data-type variable-name[size];
0.
Integer Array [0] [1] [2] [3] [4]  If we declare an array of size 5
int mark[5]; then its index ranges from 0 to 4.
 First element will be store at
integer
mark[0] and last element will be
stored at mark[4] not mark[5].
Float Array [0] [1] [2] [3] [4]
 Like integer and float array we can
float avg[5]; declare array of type char.
float
Read(Scan) Array Elements
Reading array without loop Reading array using loop
void main() void main()
{ {
int mark[5]; int mark[5],i;
printf("Enter array element="); for(i=0;i<5;i++)
scanf("%d",&mark[0]); {
printf("Enter array element="); printf("Enter array element=");
scanf("%d",&mark[1]); scanf("%d",&mark[i]);
printf("Enter array element="); }
scanf("%d",&mark[2]); for(i=0;i<5;i++)
printf("Enter array element="); {
scanf("%d",&mark[3]); printf("%d",mark[i]);
printf("Enter array element="); }
scanf("%d",&mark[4]); }
printf("%d",mark[0]);
printf("%d",mark[1]);
printf("%d",mark[2]); [0] [1] [2] [3] [4]
printf("%d",mark[3]); mark[5]
printf("%d",mark[4]); } 85 75 65 55 45
Develop a program to count number of positive or negative number from an array of 10 Number
Program
void main(){
int num[10],i,pos,neg; Output
pos = 0; Enter array element=1
neg = 0; Enter array element=2
for(i=0;i<10;i++) Enter array element=3
{ Enter array element=4
printf("Enter array element="); Enter array element=5
scanf("%d",&num[i]); Enter array element=-1
} Enter array element=-2
for(i=0;i<10;i++) Enter array element=3
{ Enter array element=4
if(num[i]>0) Enter array element=5
pos=pos+1; Positive=8,Negative=2
else
neg=neg+1;
}
printf("Positive=%d,Negative=%d",pos,eg);}
Two dimensional Array in C
Syntax
 A two dimensional array can be seen as a
data-type variable-name[x][y];
table with ‘x’ rows and ‘y’ columns.
Declaration  The row number ranges from 0 to (x-1) and
int data[3][3]; //This array can hold 9 elements column number ranges from 0 to (y-1).

int data[3][3]; Column-0 Column-1 Column-2

Row-0 data[0][0] data[0][1] data[0][2]

Row-1 data[1][0] data[1][1] data[1][2]

Row-2 data[2][0] data[2][1] data[2][2]


Read(Scan) 2D Array Elements
Program
void main(){
int data[3][3],i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{ Output Enter array element=1
printf("Enter array element="); Enter array element=2
scanf("%d",&data[i][j]); Enter array element=3
} Enter array element=4
} Enter array element=5
for(i=0;i<3;i++) Enter array element=6
{ Enter array element=7
for(j=0;j<3;j++) Enter array element=8
{ Enter array element=9
printf("%d",data[i][j]); 1 2 3
} 4 5 6
printf("\n"); }} 7 8 9
Develop a program to count number of positive, negative and zero elements from 3 X 3 matrix

Program
Output
void main(){
Enter array element=9
int data[3][3],i,j,pos=0,neg=0,zero=0;
Enter array element=5
for(i=0;i<3;i++)
Enter array element=6
{
Enter array element=-3
for(j=0;j<3;j++)
Enter array element=-7
{
Enter array element=0
printf("Enter array element=");
Enter array element=11
scanf("%d",&data[i][j]);
Enter array element=13
if(data[i][j]>0)
Enter array element=8
pos=pos+1;
positive=6,negative=2,zero=1
else if(data[i][j]<0)
neg=neg+1;
else
zero=zero+1;
}
}
printf("positive=%d,negative=%d,zero=%d",pos,neg,zero)}
POINTER

● Definition: A Variable that stores the memory address of


another variable.
● The Pointer itself has its own address in memory but the value it
holds is memory address
● Accessing the pointer: Accessing the value at the memory
location the pointers points to using * Operator.
● Address of Operator (&): Retrieves the memory address of
variable.
SYNTAX OF POINTER

● Syntax: datatype *pointer_name


● Example:
● int a=10; //Declare an integer variable
int *ptr = &a; // Declare a pointer and store the address of 'a'
printf(“Value of a: %d\n”, *ptr); // Print the value of ‘a’
Declaration & Initialization of Pointer
Syntax
 p is integer pointer variable
datatype *ptr_variablename;  & is address of or referencing operator which
Example returns memory address of variable.
void main()  * is indirection or dereferencing operator which
{ returns value stored at that memory address.
int a=10, *p; // assign memory address of  & operator is the inverse of * operator
a to pointer variable p
p = &a;
 x = a is same as x = *(&a)
printf("%d %d %d", a, *p, p);
}
Output
10 10 5000
USAGE OF POINTER
1. Dynamic Memory Allocation: Using Functions like malloc() and free() for
memory management.
2. Array and String Manipulation: Pointers can iterate through arrays or
handle strings efficiently.
3. Passing Arguments to Functions: Pointers allow passing arguments by
reference, enabling modifications in the caller's scope.
4. Data Structures: Essential for implementing linked lists, trees, and other
complex structures.
5. Function Pointers: Type of pointers that stores the address of a function,
allowing functions to be passed as arguments and invoked dynamically
EXAMPLE OF POINTER
TYPES OF POINTER
1. NULL POINTER
2. VOID POINTER
3. FUNCTION POINTER
NULL POINTER
● A NULL pointer is a pointer that does not point to any valid memory address. It is
initialized to NULL.
● Prevents uninitialized pointers.
● It can’t be dereferenced.
● Syntax : datatype *pointer_name = NULL;

#include <stdio.h> Real-World Analogy


int main() { A NULL pointer is like a remote control without
int *ptr = NULL; // Declare a NULL pointer batteries. It exists but doesn't control anything
if (ptr == NULL) { yet.
printf("Pointer is NULL, not pointing to any
memory.\n");
}
return 0;
}
Void Pointer
● A void pointer is a generic pointer that can hold the address of any data type.
● Cannot be dereferenced directly; must be cast to the appropriate type first.
● It can be used for typecasting.
● Syntax : void *pointer_name;

#include <stdio.h>
int main() {
int x = 42; Real-World Analogy
void *ptr = &x; // Void pointer holds the A void pointer is like a universal adapter that fits
address of an integer any type of plug. You need to know what type
printf("Value of x using void pointer: %d\n", you're dealing with to use it.
*(int *)ptr); // Cast to int* before dereferencing
return 0;
}
NULL POINTER VS VOID POINTER
Function Pointer
● Points to the address of a function/code but not data.
● Do not allocate de-allocate memory using function pointers.
● Syntax: return_type (*pointer_name)(parameter_list);
● Useful for callbacks, event handling, or implementing polymorphism..
#include <stdio.h>

void greet() {
Real-World Analogy
printf("Hello, World!\n");
A function pointer is like a bookmark for a
}
recipe. You can quickly jump to the recipe
(function) and execute it.
int main() {
void (*funcPtr)() = greet; // Declare and
initialize a function pointer
funcPtr(); // Call the function via the pointer
return 0;
}
FUNCTION POINTER
Function pointer can be used in place of switch
case.
// fun_ptr_arr is an array of function pointers
void add(int a, int b) {
void (*fptrArr[])(int, int)
printf("Addition is %d\n", a + b);
= { add, sub, mul };
}
unsigned int ch, a = 15, b = 10;
void sub(int a, int b) {
printf("Enter Choice: 0 for add, 1 for subtract and 2 "
printf("Subtraction is %d\n", a - b);
"for multiply\n");
}
scanf("%d", &ch);
void mul(int a, int b) {
if (ch > 2)
printf("Multiplication is %d\n", a * b);
return 0;
}
(*fptrArr[ch])(a, b);
int main() {
return 0;
}
What is a Function?
● A function in C is a block of code that performs a specific task. It can take
input, process it, and return a result.
● Functions help organize code, avoid repetition, and improve readability.

Key Points
• Declaration: Tells the compiler about the function name, return type, and
parameters.
• Definition: Contains the actual code for the function.
• Invocation: Calling the function to execute its code.
Syntax
return_type function_name(parameters) { // Function declaration
int myFunction(int x, int y);
// Code
return value; // The main method
} int main() {
int result = myFunction(5, 3); // call the
function
printf("Result is = %d", result);
return 0;
}
Example
Real-World Analogy
// Function definition
int myFunction(int x, int y) {
A function is like a coffee machine. You
return x + y;
input coffee beans and water (parameters),
}
and it gives you coffee (output).
Call By Reference :
● In Call by Reference, a function receives the memory address (reference) of
the variables as arguments instead of their actual values.
● This allows the function to directly modify the original variables in the caller's
scope.

Key Points
• Memory Sharing: The function operates on the same memory locations as the original
variables.
• Uses Pointers: Arguments are passed using pointers to the variables.
• Modifies Original Values: Any changes made inside the function reflect in the original
variables.
• Efficient for Large Data: Reduces memory usage by avoiding copying large data structures.
Example: Swapping Two Numbers (Call by Value)

#include <stdio.h> int main() {


// Function to swap two numbers using Call by int x = 5, y = 10;
Reference
printf("Before swap: x = %d, y =
void swap(int a, int b) { %d\n", x, y);
swap(x, y); // Passing addresses of x and
int temp = a; // Store the value at address a y
a = b;// Assign value at address b to address a printf("After swap: x = %d, y =
%d\n", x, y);
b = temp; // Assign temp value to address b
return 0;
}
}
Ex: Swapping Two Numbers (Call by Reference)

#include <stdio.h> int main() {


// Function to swap two numbers using Call by int x = 5, y = 10;
Reference
printf("Before swap: x = %d, y =
void swap(int *a, int *b) { %d\n", x, y);
swap(&x, &y); // Passing addresses of x
int temp = *a; // Store the value at address a and y
*a = *b;// Assign value at address b to address a printf("After swap: x = %d, y =
%d\n", x, y);
*b = temp; // Assign temp value to address b
return 0;
}
}
Example

Output :
Before swap: x = 5, y = 10
After swap: x = 10, y = 5 Key Benefits of Call by Reference

Real-World Analogy Direct Modification: Changes reflect in


the original variable.
Call by Reference is like giving someone
your house key. Memory Efficiency: Saves space,
especially for large data.
You’re not giving them a duplicate of
your house, but access to the actual house. Multiple Return Values: Functions can
modify multiple variables.
They can rearrange the furniture (modify
variable values) directly.
EXAMPLE
#include <stdio.h>

void updateValue(int *num) {


*num = 50; // Modify the value at the pointer
}
int main() {
int x = 10;
printf("Before: %d\n", x);
updateValue(&x); // Pass the address of x
printf("After: %d\n", x);
return 0;
}
MEMORY MANAGEMENT
MEMORY ALLOCATION
MEMORY MANAGEMENT
MEMORY MANAGEMENT
MEMORY MANAGEMENT
IMPORTANCE OF DYNAMIC MEMORY ALLOCATION
MALLOC(MEMORY ALLOCATION)
MALLOC(MEMORY ALLOCATION)
● Purpose: Allocates a specified number of bytes in memory and returns a pointer to the
first byte. Useful when exact memory size is known.
● Malloc stands for Memory Allocation and is used in C to dynamically allocate a specified
amount of memory during program execution
● Syntax:
void* malloc(size_t size);
● Example:
int *arr = (int*)malloc(5 * sizeof(int)); // Allocates memory for 5 integers
EXAMPLE OF MALLOC
CALLOC(CONTIGUOUS ALLOCATION)
CALLOC(CONTIGUOUS ALLOCATION)
● Purpose: Allocates memory for an array of elements and initializes all bytes to zero.
● Syntax:
void* calloc(size_t num, size_t size);
● Difference from malloc:

calloc takes two parameters: the number of elements and the size of each element

● Example:

int *arr = (int*)calloc(5, sizeof(int)); // Allocates and initializes memory for 5 integers
EXAMPLE
REALLOC(REALLOCATION)
● ”re-alloc” or “re-allocation” method in C is used to dynamically change the
memory allocation of a previously allocated memory.

● In other words, if the memory previously allocated with the help of malloc or
calloc is insufficient, realloc can be used to dynamically re-allocate memory

● Re-allocation of memory maintains the already present value and new blocks
will be initialized with the default garbage value.
REALLOC(REALLOCATION)
● Purpose: Resizes an already allocated memory block to a new size

● Syntax: void* realloc(void* ptr, size_t new_size);

● Behavior: If the new size is larger, additional memory is allocated.


EXAMPLE
FREE(FREE ALLOCATED MEMORY)
Purpose: Deallocates memory previously allocated by malloc, calloc, or realloc.
Syntax:
void free(void* ptr);
EXAMPLE
COMPARISON
ARRAY OF POINTERS
● An array of pointers is a collection of pointers where each pointer stores the address of variable,
rather than holding actual values directly.
● Each element in the array is a pointer that can point to an object of the specified type (e.g., int,
char).
● Useful for managing dynamic arrays where each element points to a different memory location.
● Syntax:
data_type *array_name[size]
● Example:
int *arr[5]; // Array of 5 integer pointers
ARRAY OF POINTERS
EXAMPLE
PROGRAM APPLICATION
● Dynamic memory allocation is a programming technique that allows
programmers to allocate and deallocate memory while a program is running.

● Applications: Dynamic Arrays, Dynamic data structures,

● Pointers enable dynamic memory allocation, efficient data manipulation, and


the implementation of complex structures.

● Proper handling of pointers (initialization, allocation, and freeing memory) is


critical to avoid errors like segmentation faults and memory leaks.
DANGLING POINTER
● A Dangling Pointer is a pointer that pointing a memory location that has been freed or deallocated.
Accessing such memory lead to undefined behavior, as the pointer is pointing to invalid memory.
● Dangling pointers lead to undefined behavior and are a common cause of segmentation faults.
● Always nullify pointers after freeing memory.
● Avoid returning the addresses of local variables or accessing out-of-scope variables.

Causes of Dangling Pointers

1. Deallocating Memory:
○ The pointer still references memory that has been freed using free().
2. Returning Local Variables:
○ Returning the address of a local variable from a function.
3. Pointer Out of Scope:
○ The pointer points to a memory location that goes out of scope.
MEMORY DEALLOCATION IN DANGLING POINTER
RETURNING LOCAL VARIABLE ADDRESS
VARIABLE GOES OUT OF SCOPE
FUNCTION CALL – SEGMENTATION FAULT
FUNCTION CALL – SEGMENTATION FAULT
THANK YOU

You might also like