C programming stdlib.h function - void *malloc(size_t size)

www.i‮aeditfig‬.com

The malloc function is a memory allocation function in the C standard library that is used to allocate a block of memory of a specified size. The syntax of the malloc function is as follows:

void *malloc(size_t size);

The size argument is the number of bytes to allocate.

The malloc function returns a pointer to the first byte of the allocated memory block. If the function is unable to allocate the requested amount of memory, it returns a null pointer.

Here is an example that demonstrates how to use the malloc function:

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

int main(void) {
    int *ptr = (int *)malloc(10 * sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (int i = 0; i < 10; i++) {
        ptr[i] = i;
    }

    for (int i = 0; i < 10; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");

    free(ptr);
    return 0;
}

In this example, the malloc function is used to allocate memory for an array of 10 int elements. The size of each element is sizeof(int). The program then uses a for loop to fill the array with values, and another for loop to print out the elements of the array. Finally, the free function is called to deallocate the memory block pointed to by ptr. Note that the malloc function returns a void pointer, which is then cast to an int pointer using a type cast (int *). This is necessary because the malloc function does not know what type of data the allocated memory will hold.