malloc() Function

The malloc() function in C dynamically allocates a block of memory and returns a pointer to its beginning. The allocated memory is uninitialized and may contain indeterminate values until explicitly set by the programmer. It is widely used for creating arrays, structures, and other data types during runtime.


Syntax of malloc()

</>
Copy
void *malloc(size_t size);

Parameters

ParameterDescription
sizeThe number of bytes to allocate. (The type size_t is an unsigned integral type.)

Return Value

On success, malloc() returns a pointer to the beginning of the allocated memory block. On failure, it returns a null pointer. The pointer is of type void* and should be cast to the appropriate type before usage.

Additional points to note:

  • The allocated memory is uninitialized, meaning it may contain garbage values.
  • If the requested size is zero, the return value is implementation-dependent and should not be dereferenced.
  • Always check if the returned pointer is null before using it to avoid undefined behavior.

Examples for malloc()

Example 1: Allocating Memory for an Integer Array and Initializing It

This example demonstrates how to allocate memory for an array of integers using malloc(), initialize the array, and print its contents.

Program

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

int main() {
    int n = 5;
    int *arr = (int *)malloc(n * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    
    // Initialize array elements
    for (int i = 0; i < n; i++) {
        arr[i] = i + 1;
    }
    
    // Print array elements
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    // Free allocated memory
    free(arr);
    return 0;
}

Explanation:

  1. An integer n is defined to represent the number of elements.
  2. malloc() is called to allocate memory for an array of n integers.
  3. The returned pointer is checked to ensure that memory allocation was successful.
  4. The array is initialized with consecutive integer values starting from 1.
  5. The array elements are printed to the console.
  6. The allocated memory is freed using free() to prevent memory leaks.

Output:

1 2 3 4 5

Example 2: Allocating Memory for a Structure and Accessing Its Members

This example demonstrates how to allocate memory for a structure using malloc(), initialize its members, and display the structure’s contents.

Program

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

typedef struct {
    char name[50];
    int age;
} Person;

int main() {
    Person *p = (Person *)malloc(sizeof(Person));
    if (p == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    
    // Initialize structure members
    strcpy(p->name, "Alice");
    p->age = 30;
    
    // Print structure details
    printf("Name: %s, Age: %d\n", p->name, p->age);
    
    // Free allocated memory
    free(p);
    return 0;
}

Explanation:

  1. A structure Person is defined with a character array for the name and an integer for the age.
  2. malloc() allocates memory for one Person object.
  3. The returned pointer is checked to ensure that memory allocation was successful.
  4. The structure members are initialized with appropriate values.
  5. The structure’s details are printed to the console.
  6. The allocated memory is freed using free() to avoid memory leaks.

Output:

Name: Alice, Age: 30