Which library function is used to allocate memory dynamically in c

which library function is used to allocate memory dynamically in c

@LectureNotes The library function used to allocate memory dynamically in C is the malloc() function.

Answer:
The malloc() function in C is used to allocate memory dynamically during program execution. It stands for “memory allocation” and is defined in the <stdlib.h> header file.

To use the malloc() function, you need to specify the amount of memory you want to allocate in bytes. It returns a pointer to the allocated memory, which can be used to access and manipulate the data stored in that memory.

Here’s an example of how to use the malloc() function:

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

int main() {
    int *ptr;
    int size;

    printf("Enter the size of the array: ");
    scanf("%d", &size);

    // Allocate memory dynamically
    ptr = (int*) malloc(size * sizeof(int));

    if (ptr == NULL) {
        printf("Memory allocation failed.");
        return 0;
    }

    // Use the allocated memory
    for (int i = 0; i < size; i++) {
        ptr[i] = i + 1;
        printf("%d ", ptr[i]);
    }

    // Free the allocated memory
    free(ptr);

    return 0;
}

In this example, we allocate memory dynamically using malloc() to create an array of integers with a size specified by the user. We then use the allocated memory to store values and print them. Finally, we free the memory using the free() function to release it back to the system.

It’s important to note that after allocating memory dynamically with malloc(), you should always free the memory using the free() function when you no longer need it. Failing to do so can lead to memory leaks.