C Allocate Memory

In C programming, memory allocation is performed using dynamic memory allocation functions from the stdlib.h library. The malloc() function is used to allocate memory dynamically during program execution.

Key Topics

1. Using malloc()

The malloc() function allocates a specified number of bytes and returns a pointer to the first byte of the allocated memory. The memory is uninitialized.

Example: Allocating Memory for an Integer

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

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

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

    *ptr = 42;
    printf("Value: %d\n", *ptr);

    free(ptr);
    return 0;
}

Code Explanation: The malloc() function allocates memory for an integer and returns a pointer to it. The allocated memory is then freed using the free() function.