Memory Allocation
Memory Allocation
Explanation
Consider the declaration, int i = 3 ;
This declaration tells the C compiler to:
a. Reserve space in memory to hold the integer value.
b. Associate the name i with this memory location.
c. Store the value 3 at this location.
main( ) output:
{
1
int i = 3 ;
int *j ;
j = &i ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nAddress of i = %u", j ) ;
printf ( "\nAddress of j = %u", &j ) ;
printf ( "\nValue of j = %u", j ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
printf ( "\nValue of i = %d", *j ) ;
}
Memory allocation in c refers to the process of reserving space in
memory for variables, arrays, or dynamically created data during the
execution of a program.
Syntax:
ptr = (cast-type*) malloc(byte-size);
Example:
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 2 bytes, this statement will allocate 200 bytes of memory.
And, the pointer ptr holds the address of the first byte in the allocated memory.
If space is insufficient, allocation fails and returns a NULL pointer.
2. calloc() function
Syntax:
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.
Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with
the size of the float.
3
3. realloc() function
• “realloc” or “re-allocation” method is used to dynamically change the
memory allocation of a previously allocated memory.
• 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.
Syntax:
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'. If space is insufficient, allocation
fails and returns a NULL pointer.
4. free() function
• Used to deallocate memory that was previously allocated with malloc, calloc,
or realloc. It marks the memory as available for reuse.
• The memory allocated using functions malloc() and calloc() is not de-
allocated on their own. Hence the free() method is used, whenever the
dynamic memory allocation takes place. It helps to reduce wastage of
memory by freeing it.
Syntax:
free(ptr);
Output:
The elements of the array are: 1, 2, 3, 4, 5,
The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10