乐闻世界logo
搜索文章和话题

How do malloc() and free() work?

1个答案

1

malloc() and free() are two fundamental functions in the C standard library used for dynamic memory allocation. I will now provide a detailed explanation of how these functions operate, along with a practical example.

malloc() Function

The malloc() function dynamically allocates a memory block of a specified size on the heap. Its prototype is defined in the <stdlib.h> header file as follows:

c
void* malloc(size_t size);

Here, size_t size specifies the memory size in bytes to be allocated. If the allocation succeeds, malloc() returns a pointer to the allocated block. If it fails (e.g., due to insufficient memory), it returns NULL.

malloc() only allocates memory without initialization. Consequently, the contents of the allocated memory are undefined, and the user must initialize this block explicitly.

free() Function

The free() function releases memory previously allocated by malloc(). Its prototype is also defined in <stdlib.h>:

c
void free(void* ptr);

Here, void* ptr is a pointer to the memory block allocated by malloc(). free() deallocates this memory, making it available for future allocations. After freeing memory with free(), the original pointer becomes a dangling pointer, and accessing it again is unsafe. It is a good practice to set the pointer to NULL after freeing memory to avoid such issues.

Example

The following example demonstrates the use of malloc() and free():

c
#include <stdlib.h> #include <stdio.h> int main() { int n = 5; // Allocate memory for 5 integers int* arr = (int*) malloc(n * sizeof(int)); if (arr == NULL) { fprintf(stderr, "Memory allocation failed\n"); return 1; } // Initialize the array for (int i = 0; i < n; i++) { arr[i] = i; } // Output the array for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); // Release memory free(arr); arr = NULL; // Prevent dangling pointer return 0; }

In this example, malloc() is first used to allocate memory for 5 integers. The array is then initialized by iterating through it, followed by output. Finally, free() releases the memory, and the pointer is set to NULL to avoid dangling pointer problems.

By employing this approach, malloc() and free() enable effective management of dynamic memory in C programs, enhancing flexibility and efficiency in memory usage.

2024年6月29日 12:07 回复

你的答案