C malloc
Created By: chatGPT
C's
malloc
(memory allocation) function is used to dynamically allocate memory during program execution. It is part of the C standard library and is declared in the <stdlib.h>
header file. Memory allocated using malloc
must be explicitly freed when no longer needed to prevent memory leaks. The function returns a pointer to the allocated memory, or NULL
if the allocation fails. The size of the allocated memory is specified in bytes as an argument to malloc
. Here’s a basic usage example:#include <stdio.h>
#include <stdlib.h>
int main() {
int *array;
int n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
// Dynamically allocate memory
array = (int*)malloc(n * sizeof(int));
if (array == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// Initialize and display array elements
for (i = 0; i < n; i++) {
array[i] = i + 1; // Assigning values
printf("Element[%d]: %d\n", i, array[i]);
}
// Free the allocated memory
free(array);
return 0;
}
In the example above, we request the user for the number of elements for an array. Then, we call
malloc
to allocate enough memory to hold n
integers. We check if malloc
returned NULL
, which indicates a failure to allocate memory. If successful, we can use the allocated memory as an array and later free it using the free
function, ensuring to manage memory responsibly.#include <stdio.h>
#include <stdlib.h>
int main() {
// Sample function to show malloc usage
void *ptr;
ptr = malloc(10 * sizeof(int)); // Allocates memory for 10 integers
if (ptr == NULL) {
printf("Allocation failed\n");
return -1;
}
// Usage of the allocated memory...
free(ptr); // Free the allocated memory
return 0;
}