Zone Of Makos

Menu icon

malloc in C

In the C programming language, malloc is a library function that is used to dynamically allocate memory during program execution. It stands for "memory allocation". The malloc function allows you to request a specific amount of memory from the system and returns a pointer to the allocated memory block. This dynamically allocated memory can be used to store data as per your program's requirements. In this lesson, we'll explore how to use malloc in C and understand its importance in memory management.

Syntax of malloc

The syntax for using malloc in C is as follows:


#include <stdlib.h>

void* malloc(size_t size);

The malloc function takes a single argument of type size_t , which represents the number of bytes of memory to be allocated. It returns a void pointer ( void* ) to the allocated memory block. Since the return type is a void pointer, you need to explicitly cast it to the desired data type when using the allocated memory.

Example Usage

Here's an example that demonstrates how to use malloc to dynamically allocate memory for an integer:


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

int main() {
    int* ptr;
    int size = 5;
    
    // Allocate memory for an array of integers
    ptr = (int*)malloc(size * sizeof(int));
    
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    
    // Access and modify the allocated memory
    for (int i = 0; i < size; i++) {
        ptr[i] = i + 1;
    }
    
    // Print the values stored in the allocated memory
    for (int i = 0; i < size; i++) {
        printf("%d ", ptr[i]);
    }
    
    // Free the allocated memory
    free(ptr);
    
    return 0;
}

In this example, we first declare a pointer ptr of type int* to store the allocated memory address. We then use malloc to allocate memory for an array of integers with a size of size (which is set to 5 in this case). We check if the memory allocation was successful by comparing the ptr to NULL . If it is NULL , it means that the memory allocation failed. Otherwise, we can access and modify the allocated memory as needed. Finally, we free the allocated memory using the free function to release it back to the system.

Conclusion

The malloc function in C provides a way to dynamically allocate memory during program execution. It allows you to request a specific amount of memory and returns a pointer to the allocated memory block. Proper usage of malloc is essential for efficient memory management in C programs. Remember to free the allocated memory using the free function when you no longer need it to prevent memory leaks.