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()
void *malloc(size_t size);
Parameters
Parameter | Description |
---|---|
size | The 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
#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:
- An integer
n
is defined to represent the number of elements. malloc()
is called to allocate memory for an array ofn
integers.- The returned pointer is checked to ensure that memory allocation was successful.
- The array is initialized with consecutive integer values starting from 1.
- The array elements are printed to the console.
- 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
#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:
- A structure
Person
is defined with a character array for the name and an integer for the age. malloc()
allocates memory for onePerson
object.- The returned pointer is checked to ensure that memory allocation was successful.
- The structure members are initialized with appropriate values.
- The structure’s details are printed to the console.
- The allocated memory is freed using
free()
to avoid memory leaks.
Output:
Name: Alice, Age: 30