The C programming language provides several functions for memory allocation and management. These functions can be found in the <stdlib.h> header file.
Sr.No. | Function & Description |
---|---|
1 | void *calloc(int num, int size> ; This function allocates an array of num elements each of which size in bytes will be size. |
2 | void free(void *address> ; This function releases a block of memory block specified by address. |
3 | void *malloc(size_t size> ; This function allocates an array of num bytes and leave them uninitialized. |
4 | void *realloc(void *address, int newsize> ; This function re-allocates memory extending it upto newsize. |
char name[100];But now let us consider a situation where you have no idea about the length of the text you need to store, for example, you want to store a detailed description about a topic. Here we need to define a pointer to character without defining how much memory is required and later, based on requirement, we can allocate memory as shown in the below example −
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(>When the above code is compiled and executed, it produces the following result.
{ char name[100]; char *description; strcpy(name, "Zara Ali">
; /* allocate memory dynamically */ description = malloc( 200 * sizeof(char>
>
; if( description == NULL >
{ fprintf(stderr, "Error - unable to allocate required memory\n">
; } else { strcpy( description, "Zara ali a DPS student in class 10th">
; } printf("Name = %s\n", name >
; printf("Description: %s\n", description >
; }
Name = Zara Ali Description: Zara ali a DPS student in class 10thSame program can be written using calloc(>
calloc(200, sizeof(char>So you have complete control and you can pass any size value while allocating memory, unlike arrays where once the size defined, you cannot change it.
>
;