C - Tutorial
     

C - Dynamic Memory

Dynamic Memory

In dynamic memory allocation technique, allocation of memory is done at the time of running the program, and it also has the facility to increase/decrease the memory quantity allocated and can also release or free the memory as and when not required or used. Reallocation of memory can also be done when required. So, it is more advantageous, and memory can be managed efficiently.

malloc, calloc, or realloc are the three functions used to manipulate memory. These commonly used functions are available through the stdlib library so you must include this library to use them.

This chapter explains dynamic memory management in C. The C programming language provides several functions for memory allocation and management. These functions can be found in the header file.

Function Description
void *calloc(int num, int size) This function allocates an array of num elements each of which size in bytes will be size.
void free(void *address) This function releases a block of memory block specified by address.
void *malloc(size_t size) This function allocates an array of num bytes and leave them uninitialized.
void *realloc(void *address, int newsize) This function re-allocates memory extending it upto newsize.

Allocating Memory Dynamically Using malloc()

While programming, if you are aware of the size of an array, then it is easy and you can define it as an array. For example, to store a name of any person, it can go up to a maximum of 100 characters, so you can define something as follows.

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() {

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 );

}

When the above code is compiled and executed, it produces the following result.

Name = Zara Ali

Description: Zara ali a DPS student in class 10th

calloc() Function

The calloc() in C is a function used to allocate multiple blocks of memory having the same size. It is a dynamic memory allocation function that allocates the memory space to complex data structures such as arrays and structures and returns a void pointer to the memory. Calloc stands for contiguous allocation.

Malloc function is used to allocate a single block of memory space while the calloc function in C is used to allocate multiple blocks of memory space. Each block allocated by the calloc in C programming is of the same size.

calloc() Syntax:

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

  • The above statement example of calloc in C is used to allocate n memory blocks of the same size.
  • After the memory space is allocated, then all the bytes are initialized to zero.
  • The pointer which is currently at the first byte of the allocated memory space is returned.

Whenever there is an error allocating memory space such as the shortage of memory, then a null pointer is returned as shown in the below calloc example:

#include <stdio.h>

int main() {

int i, * ptr, sum = 0;

ptr = calloc(10, sizeof(int));

if (ptr == NULL) {

printf("Error! memory not allocated.");

exit(0);

}

printf("Building and calculating the sequence sum of the first 10 terms \ n ");

for (i = 0; i < 10; ++i) { * (ptr + i) = i;

sum += * (ptr + i);

}

printf("Sum = %d", sum);

free(ptr);

return 0;

} Result of the calloc in C example:

Building and calculating the sequence sum of the first 10 terms

Sum = 45

realloc() Function

realloc() is a function of C library for adding more memory size to already allocated memory blocks. The purpose of realloc in C is to expand current memory blocks while leaving the original content as it is. realloc() function helps to reduce the size of previously allocated memory by malloc or calloc functions. realloc stands for reallocation of memory.

Syntax for realloc() in C

ptr = realloc (ptr,newsize);

The above statement allocates a new memory space with a specified size in the variable newsize. After executing the function, the pointer will be returned to the first byte of the memory block. The new size can be larger or smaller than the previous memory. We cannot be sure that if the newly allocated block will point to the same location as that of the previous memory block. The realloc function in C will copy all the previous data in the new region. It makes sure that data will remain safe.

For example:

#include <stdio.h>

int main () {

char *ptr;

ptr = (char *) malloc(10);

strcpy(ptr, "Programming");

printf(" %s, Address = %u\n", ptr, ptr);

ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size

strcat(ptr, " In 'C'");

printf(" %s, Address = %u\n", ptr, ptr);

free(ptr);

return 0;

}

How to use realloc()

The below program in C demonstrates how to use realloc in C to reallocate the memory.

#include <stdio.h>

#include <stdlib.h>

int main() {

int i, * ptr, sum = 0;

ptr = malloc(100

if (ptr == NULL) {

printf("Error! memory not allocated.");

exit(0);

}

ptr = realloc(ptr,500);

if(ptr != NULL)

printf("Memory created successfully\n");

return 0;

}

Result of the realloc in C example:

Memory created successfully

Whenever the realloc results in an unsuccessful operation, it returns a null pointer, and the previous data is also freed.

free() Function

The free() function in C library allows you to release or deallocate the memory blocks which are previously allocated by calloc(), malloc() or realloc() functions. It frees up the memory blocks and returns the memory to heap. It helps freeing the memory in your program which will be available for later use.

In C, the memory for variables is automatically deallocated at compile time. For dynamic memory allocation in C, you have to deallocate the memory explicitly. If not done, you may encounter out of memory error.

free() Syntax:

void free(void *ptr)

Here, ptr is the memory block that needs to be deallocated.

Now, let’s learn how to use function of free in C language with an example.

#include <stdio.h>

int main() {

int* ptr = malloc(10 * sizeof(*ptr));

if (ptr != NULL){

*(ptr + 2) = 50;

printf("Value of the 2nd integer is %d",*(ptr + 2));

}

free(ptr);

}

Output of the above free in C example:

Value of the 2nd integer is 50

www.jstalin.com