Your browser doesn't support JavaScript Dynamic Memory Allocation – Windows Programming

Dynamic Memory Allocation

Dynamic memory allocation is the process of requesting and releasing memory while a program is running. It allows a program to allocate memory as needed, rather than having to determine the required amount of memory in advance.

Dynamic memory allocation is particularly useful when the amount of memory required depends on information that is not known until the program executes. The programmer requests the required amount of memory and must check whether the allocation was successful.

The C standard library provides four functions for dynamic memory allocation, declared in the stdlib.h header file:

  • malloc() — allocates a block of memory of a specified size.
  • calloc() — allocates memory for a specified number of elements and initialises all its bytes to zero.
  • realloc() — changes the size of a previously allocated memory block.
  • free() — releases memory that was previously allocated dynamically.

The amount of memory available for allocation depends on the system and the resources available to the program. Allocation functions that return a pointer must be checked for failure; malloc(), calloc() and realloc() return NULL if they cannot allocate the requested memory.

Dynamically allocated memory remains allocated until it is released using free() or until the program terminates. Failing to release memory that is no longer needed can lead to memory leaks.

The malloc() Function

The malloc() function allocates a block of memory of the specified size in bytes. It returns a pointer of type void *, which can be assigned to a pointer of another object type in C without an explicit cast.

The function prototype is:

void *malloc(size_t size);

The size parameter specifies the number of bytes to allocate. If the allocation fails, malloc() returns NULL. The allocated memory is uninitialised, so its contents must be set before they are read.

Example

The following program uses malloc() to allocate memory for a string and an integer.

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

int main(void)
{
    char *str;

    /* Allocate memory for a string */
    str = malloc(25 * sizeof(char));

    if (str == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    strcpy(str, "malloc memory string");

    printf("String = %s, Address = %p\n", str, (void *)str);

    /* Allocate memory for an integer */
    int *i = malloc(sizeof(int));

    if (i == NULL) {
        printf("Memory allocation failed.\n");
        free(str);
        return 1;
    }

    *i = 100;

    printf("Integer = %d, Address = %p\n", *i, (void *)i);

    /* Release allocated memory */
    free(str);
    free(i);

    return 0;
}

Example output:
String = malloc memory string, Address = 0x12345678
Integer = 100, Address = 0x123456a0

The memory addresses shown are illustrative; actual addresses will vary between executions and systems.

In this example:

  • malloc(25 * sizeof(char)) allocates enough memory for 25 characters, including the terminating null character.
  • strcpy() copies the string into the allocated memory.
  • malloc(sizeof(int)) allocates enough memory to store one integer.
  • *i = 100 stores the value 100 in the allocated memory.
  • %p is used to display a pointer address.
  • free() releases the allocated memory when it is no longer needed.

Important: Always check whether malloc() returns NULL before using the allocated memory. Also, allocate enough memory for the data you intend to store. For example, malloc(1) is not sufficient space for an ordinary int on most systems.

The calloc() function

The calloc() function allocates memory for a specified number of elements, with each element having the same size. Unlike malloc(), calloc() initialises all the allocated bytes to zero.

The function prototype is:

void *calloc(size_t nitems, size_t size);

The parameters are:

  • nitems — the number of elements to allocate.
  • size — the size of each element in bytes.

The function returns a pointer to the allocated memory or NULL if the allocation fails.

Example

The following program uses calloc() to allocate memory for four integers, assigns values to them and displays the results.

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

int main(void)
{
    int *ptr;

    // Allocate memory for four integers
    ptr = calloc(4, sizeof(int));

    if (ptr == NULL) {
        puts("Memory allocation failed.");
        return 1;
    }

    puts("Memory allocation was successful.");

    // Assign values to the allocated elements
    for (int i = 0; i < 4; i++) {
        ptr[i] = i;
    }

    // Display the elements
    for (int i = 0; i < 4; i++) {
        printf("[%d]", ptr[i]);
    }

    printf("\n");

    // Release the allocated memory
    free(ptr);

    return 0;
}

Output:
Memory allocation was successful.
[0][1][2][3]

In this example:

  • calloc(4, sizeof(int)) allocates enough memory for four integers.
  • sizeof(int) determines the number of bytes required for one integer.
  • ptr[i] accesses each element of the allocated memory.
  • The allocation is checked against NULL before the pointer is used.
  • free(ptr) releases the allocated memory.

Note: Because calloc() initialises the allocated bytes to zero, all four integers initially have the value 0. The for loop subsequently replaces those values with 0, 1, 2 and 3.

The realloc() Function 

The realloc() function changes the size of a block of memory that was previously allocated dynamically using malloc(), calloc() or realloc(). It can increase or decrease the size of the memory block as required.

The function prototype is:

void *realloc(void *ptr, size_t size);

The parameters are:

  • ptr — a pointer to the previously allocated memory block.
  • size — the new size of the memory block in bytes.

The function returns a pointer to the resized memory block. The memory block may be moved to a different location, so the returned pointer should always be used. If the allocation fails, realloc() returns NULL and the original memory block remains valid.

If realloc() is successful, the existing data is preserved up to the smaller of the old and new sizes. If the block grows, the additional memory is uninitialised.

Example

The following program allocates memory for two integers and then increases the allocation to hold four integers.

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

int main(void)
{
    int *ptr = malloc(2 * sizeof(int));

    if (ptr == NULL) {
        puts("Memory allocation failed.");
        return 1;
    }

    ptr[0] = 10;
    ptr[1] = 20;

    // Increase the allocation to hold four integers
    int *temp = realloc(ptr, 4 * sizeof(int));

    if (temp == NULL) {
        puts("Memory reallocation failed.");
        free(ptr);
        return 1;
    }

    ptr = temp;

    // Assign values to the additional elements
    ptr[2] = 30;
    ptr[3] = 40;

    // Display all four elements
    for (int i = 0; i < 4; i++) {
        printf("%d ", ptr[i]);
    }

    printf("\n");

    free(ptr);

    return 0;
}

Output:
10 20 30 40

In this example:

  • malloc() initially allocates memory for two integers.
  • realloc() increases the allocation to hold four integers.
  • The temporary pointer temp ensures that the original pointer is not lost if reallocation fails.
  • The original two values are preserved, and values are assigned to the two additional elements.
  • free() releases the allocated memory when it is no longer needed.

Important: Avoid assigning the result of realloc() directly to the original pointer, as this can lose access to the original allocation if reallocation fails. Also, do not use realloc(ptr, 0) to release memory; use free(ptr) instead.

The free() function

Memory allocated dynamically using malloc(), calloc() or realloc() should be released when it is no longer needed. The free() function releases the allocated memory, making it available for future allocations.

The function prototype is:

void free(void *ptr);

The ptr parameter is a pointer to a memory block previously allocated by a dynamic memory allocation function. Calling free() with a pointer that was not allocated dynamically, or freeing the same memory more than once, results in undefined behaviour.

Example

The following program demonstrates how memory can be allocated, expanded, reduced and eventually released.

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

int main(void)
{
    char *str;

    // Initial memory allocation
    str = malloc(20 * sizeof(char));

    if (str == NULL) {
        puts("Memory allocation failed.");
        return 1;
    }

    strcpy(str, "malloc memory string");
    printf("String = %s\n", str);

    // Expand the memory allocation
    char *temp = realloc(str, 60 * sizeof(char));

    if (temp == NULL) {
        puts("Memory reallocation failed.");
        free(str);
        return 1;
    }

    str = temp;

    strcpy(str, "expand malloc memory string");
    printf("Expanded string = %s\n", str);

    // Shrink the memory allocation
    temp = realloc(str, 15 * sizeof(char));

    if (temp == NULL) {
        puts("Memory reallocation failed.");
        free(str);
        return 1;
    }

    str = temp;

    strcpy(str, "shrink memory");
    printf("Shrunk string = %s\n", str);

    // Release the allocated memory
    free(str);
    str = NULL;

    return 0;
}

Output:
String = malloc memory string
Expanded string = expand malloc memory string
Shrunk string = shrink memory

In this example:

  • malloc() allocates memory for the initial string.
  • realloc() increases the allocation to 60 bytes, allowing a longer string to be stored.
  • A second call to realloc() reduces the allocation to 15 bytes, enough for “shrink memory” and its terminating null character.
  • The temporary pointer temp prevents the original pointer from being lost if reallocation fails.
  • free(str) releases the memory, and str = NULL clears the pointer to avoid leaving it pointing to released memory.

Important: Always check the result of malloc() and realloc() before using the returned pointer. After memory is freed, do not access the memory through that pointer.

Manipulating Memory Blocks

The C standard library provides functions for setting, copying and moving data within blocks of memory. These functions are declared in the string.h header file.

The memset() Function

The memset() function sets a specified number of bytes in a block of memory to a particular value.

The function prototype is:

void *memset(void *dest, int c, size_t count);

The parameters are:

  • dest — a pointer to the start of the memory block to be modified.
  • c — the value to be written to each byte, converted to unsigned char.
  • count — the number of bytes to modify.

The function returns the destination pointer.

Note: memset() sets bytes to a value; it does not copy or move data between memory locations.

The memcpy() Function

The memcpy() function copies a specified number of bytes from one memory block to another.

The function prototype is:

void *memcpy(void *dest, const void *src, size_t count);

The parameters are:

  • dest — a pointer to the destination memory block.
  • src — a pointer to the source memory block.
  • count — the number of bytes to copy.

The function returns the destination pointer.

Important: The source and destination memory blocks must not overlap. If they overlap, the behaviour is undefined. Use memmove() when overlapping blocks are possible.

The memmove() Function

The memmove() function copies a specified number of bytes from one memory block to another. Unlike memcpy(), it safely handles overlapping source and destination memory blocks.

The function prototype is:

void *memmove(void *dest, const void *src, size_t count);

The parameters are:

  • dest — a pointer to the destination memory block.
  • src — a pointer to the source memory block.
  • count — the number of bytes to copy.

The function returns the destination pointer.

Example

The following program demonstrates how memset() and memmove() can be used to manipulate the contents of character arrays.

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

char messageorg[60] = "This is the original message";
char messagenew[60] = "";

int main(void)
{
    printf("%s\n", messageorg);

    // Replace the first seven characters with spaces
    memset(messageorg, ' ', 7);
    printf("%s\n", messageorg);

    // Copy 18 bytes starting at position 12
    memmove(messagenew, messageorg + 12, 18);
    messagenew[18] = '\0';

    printf("%s\n", messagenew);

    return 0;
}

Output:
This is the original message
the original message
the original messa

In this example:

  • memset(messageorg, ‘ ‘, 7) replaces the first seven characters with spaces.
  • messageorg + 12 points to the character at index 12 in messageorg.
  • memmove() copies 18 bytes from that position into messagenew.
  • messagenew[18] = ‘\0′ adds a terminating null character so the copied data can be printed as a string.

Although this example demonstrates memset() and memmove(), memcpy() is useful for copying bytes between non-overlapping memory blocks.