Beruflich Dokumente
Kultur Dokumente
suruchi purwar
Memory Allocations in C
In static memory allocation, memory is allocated to the variables at the start of the
program while in dynamic memory allocation, memory is allocated at the run-
time.
Static memory allocation results in the inefficient use of memory while dynamic
memory allocation makes the efficient use of memory.
In dynamic memory allocation, memory can be expanded & contract during run-
time as per requirement. This provides the flexibility to the programmer.
1. Malloc( )
2. Calloc( )
1
Memory allocation in C
suruchi purwar
3. Free( )
4. Realloc( )
1. Malloc( ) :
• This function is like a request to the RAM of the system to allocate the memory,
if the request is granted, it returns a pointer to the first block of that block of
memory & the type of pointer it returns is void. And if the request is not granted
then it returns a NULL.
• Example :
int*ptr;
ptr=malloc(10*sizeof(int));
• Example of type_casting:
int*ptr;
ptr=(int*)malloc(10*sizeof(int));
2
Memory allocation in C
suruchi purwar
2. Calloc( ) :
• It works similar to the malloc() function except that it requires two argument.
• Example :
int*ptr;
ptr = (int*)calloc(10,2);
• The memory allocated by the malloc() contains garbage values & the memory
allocated by calloc() contains all zeros.
3. Free( ) :
• Free function is used to return the allocated memory block to the system
memory RAM.
3
Memory allocation in C
suruchi purwar
free(ptr);
4. Realloc( ) :
• This function is used to resize the size of memory block, which is already
allocated.
• Note that before using the realloc() function, the memory block to be
resized should be allocated using the following statement:
ptr = malloc(size);