malloc() and calloc() in C

Filed Under: C Programming
Malloc And Calloc

We use malloc() and calloc() to dynamically allocate memory on the heap.

For a program, static memory allocation is done on its stack, where a predefined amount of memory is reserved for a particular variable.

In case the size of variable changes dynamically, we need to ensure that we can dynamically manage its memory. This is where malloc() and calloc() can be used, along with the realloc() and free() functions.

Let’s understand how we can use these functions to manage the heap.


Syntax for malloc() and calloc()

malloc() is used to allocate a user-defined number of bytes on the heap.

Since we associate memory locations with pointers, this also returns a pointer to that memory location.

void* malloc(size_t size);

After we return the pointer, this will have allocated size bytes on the heap.

calloc() is similar, but it not only allocates memory but sets them to zero.

void* calloc(int num_blocks, size_t block_size);

This allocates num_blocks for the pointer, having a block size each, and sets the blocks to zero.

If the memory allocation fails for some reason, both malloc() and calloc() will return a NULL pointer.

We can typecast the void* pointer to a pointer of our choice, like int, float, etc.

NOTE: This is a part of the C standard library. So we must include the header file <stdlib.h>.

Now that we’ve seen the syntax, let’s understand them a bit more clearly using some examples.


Example for malloc()

Let’s look at an example for the malloc() function first.

#include <stdio.h>
#include <stdlib.h>

int main() {
    // Allocating memory dynamically on the heap
    // for an integer, which returns an int* pointer
    int* a = (int*) malloc (sizeof(int));
    if (a != NULL)
        printf("Allocated memory for an integer\n");
    else
        printf("malloc() failed");
    int x = 100;
    // We can update the value to this location, since
    // we have allocated memory for the pointer
    *a = x;
    printf("a points to %d\n", *a);

    int* b;
    // Will give a segmentation fault, since
    // *b is not allocated any memory
    *b = x;
    printf("b points to %d\n", *b);
    
    // Free memory from the heap
    free(a);
    return 0;
}

This example uses malloc() to allocate memory for an integer location pointed by a. Since we have allocated memory, we can update the value. But another pointer b, which is not allocated memory anywhere, cannot update its value, and we get a segmentation fault since we try to access a NULL location.

Output

Allocated memory for an integer
a points to 100
[1]    14671 segmentation fault (core dumped)  ./a.out

Example for calloc()

The calloc() function has a similar usage, but since it allocates blocks of memory, we can use it to allocate memory for arrays.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    // Allocating memory dynamically on the heap
    // for a character array of 50 characters and
    // sets each element to zero.
    char* a = (char*) calloc (50, sizeof(char));
    if (a != NULL)
        printf("Allocated memory for a character array\n");
    else
        printf("calloc() failed");

    // We can use strcpy to copy to this array, since
    // we have allocated memory
    strcpy(a, "Hello from JournalDev");

    printf("The character array is:%s\n", a);
    
    // Free the allocated memory
    free(a);

    return 0;
}

Output

Allocated memory for a character array
The character array is:Hello from JournalDev
Freed memory from the heap

References


Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages