Dynamic memory allocation in C programming language

Programming

Dynamic memory allocation – Since C is a structured language, there are some fixed programming rules for it. One of them involves modifying an array ‘s scale. An array is a set of objects in continuous memory locations that are stored.

How do you create an array using dynamic memory allocation?

An array is a collection, as you know, of a fixed number of values. When an array ‘s size is declared, you are unable to adjust it.

The array size you have declared can often be insufficient. You can allocate memory manually during run-time to solve this problem. In C programming, this is known as dynamic memory allocation.

malloc(), calloc(), realloc(), and free() are the library functions used to allocate memory dynamically. In the stdlib.h header file, that functions are specified.

The malloc Function

The malloc() feature stands for assigning memory. It is a function that is used dynamically to assign a block of memory. It reserves the specified size of the memory space and returns a null pointer pointing to the location of the memory. The returned pointer is typically of the void type. It means we can allocate any pointer to the malloc function.

Syntax:

ptr = (cast_type *) malloc (byte_size);

Example:

Dynamic memory allocation

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

The calloc Function

calloc() is another function for memory allocation that is used to allocate memory at runtime. For the allocation of memory to derived data types such as arrays and structures, the calloc function is typically used. If it fails to allocate enough space as defined, a NULL pointer is returned.

Syntax:

ptr = (cast_type *) calloc (n, size);

The realloc Function

If the dynamically allocated memory is insufficient or more than needed, you can use the realloc() function to change the size of the previously allocated memory.

Syntax:

ptr = realloc (ptr,newsize);

The free Function

The free() function frees the allocated memory through the functions malloc(), calloc(), realloc(), and returns the memory to the system.

Syntax:

free (pointer_name);