---Sujal---
Background
- compile time, runtime (to speak)
- memory layout
Static memory allocation
---Pranav---
- Memory allocated during compile time is called static memory. The allocated memory is fixed and cannot be increased or
decreased during runtime.
-
Memory allocated during compile time means that the compiler resolves the amount of memory required, where the data
will be stored, and so on at the time of compilation itself. In other words, the compiler knows everything needed to
assign memory beforehand.
-
Problems Faced in Static Memory Allocation
- If the user is allocating memory for an array during compile time, then the size should be fixed at the time of
declaration. (This approach offers the least flexibility. Since the size is fixed, the array or any object’s size
cannot be altered at run time.)
- If the values stored by the user in the array at run time is less than the size specified, then there will be
wastage of memory.
- If the values stored by the user in the array at run time is more than the size specified, then the program might
crash or misbehave.
- To solve these problems, dynamic memory allocation is preferred.
Dynamic Memory Allocation
---Dhruv---
- The process of allocating memory at the time of execution (run time) is called Dynamic Memory Allocation. Since the
size of the memory to be allocated is decided at runtime, the user has greater flexibility to allocate memory as per
his/her requirement.
Heap segment
Unlike the stack where the memory is allocated or deallocated in a defined contiguous order, the heap is an area of
memory, where memory is allocated and deallocated without any order, or randomly.
- malloc()
- malloc is a short name for memory allocation is used to dynamically allocate large blocks of contiguous memory.
- return type: void ptr
- void *ptr,
int *a = (*int) malloc(sizeof(int) * 5);
```c
int main() {
int i, n;
printf("Enter the number of integers: ");
scanf("%d", &n);
int ptr = (int )malloc(n*sizeof(int));
if (ptr == NULL) {
printf("Memory not available.");
exit(1);
}
for (i = 0; i < n; i++) {
printf("Enter an integer: ");
scanf("%d", ptr + i);
}
for (i = 0; i < n; i++)
printf("%d", *(ptr + i));
return 0;
}
```
---Pranav---
-
calloc()
- The calloc() is a built-in function used to allocate multiple blocks of memory dynamically. It is also declared in
the stdlib.h header file.
-
realloc()
- The realloc() is a built-in function used to resize the previously allocated memory block without losing the old
data. The realloc() function is also declared in the stdlib.h header file.
- The name itself says reallocation, which means changing the size of the memory block.
---Sujal---
End Slide
The End.