You are on page 1of 2

Md.

Al Momen
Id- 0242310005341154
SWE- 40A1
Class Assessment of Pointer
Course Code: SE133

1. malloc():

What it is: malloc() stands for "memory allocation." It is a standard library function in C
and
C++ used for dynamic memory allocation.

Why it is used: malloc() is used to allocate a specific amount of memory during the
program's execution. It returns a pointer to the beginning of the allocated memory
block.

Implementation: Here's a simple example in C:


int *arr = (int *)calloc(5, sizeof(int));
Advantages:

• Straightforward to use.
• Efficient for allocating a single block of memory.

Disadvantages:

• Does not initialize the allocated memory, which may contain garbage values.
• It doesn't resize the allocated memory.

2. calloc():

What it is: calloc() stands for "contiguous allocation." Like malloc(), it is a memory
allocation
function in C and C++.

Why it is used: calloc() is used to allocate a specified number of blocks of memory,


each with
a specified number of bytes. It initializes the allocated memory to zero.
Implementation:
int *arr = (int *)calloc(5, sizeof(int));

Advantages:

• Initializes the allocated memory to zero.


• Allocates a specified number of blocks of memory.

Disadvantages:

• Slightly slower than malloc() as it initializes memory.

3. realloc():

What it is: realloc() stands for "reallocate." It is a memory allocation function in C and
C++
used for resizing previously allocated memory.

Why it is used: realloc() is used to change the size of the memory block previously
allocated
by malloc(), calloc(), or realloc().

Implementation
int *newArr = (int *)realloc(arr, 10 * sizeof(int));

Advantages:

• Allows dynamic resizing of memory.


• Preserves the existing data when resizing.

Disadvantages:

• Can be a relatively expensive operation.


• May need to copy the existing data to a new location, causing performance
overhead.

You might also like