C Memory Management Guide
In C language, memory management is the responsibility of the programmer. Here are some commonly used memory management operations:
- Dynamic memory allocation:
You can use the malloc() function to allocate a block of memory of a specified size on the heap. The syntax is as follows:
int *ptr;
ptr = (int *)malloc(sizeof(int));
- Memory release:
Use the free() function to release previously allocated memory space, to avoid memory leaks. The syntax is as follows:
free(ptr);
- Reallocate memory:
Use the realloc() function to change the size of the previously allocated memory space. The syntax is as follows:
ptr = realloc(ptr, newSize);
- Memory initialization:
You can use the memset() function to initialize a block of memory to a specified value. The syntax is as follows:
memset(ptr, 0, sizeof(ptr));
It’s important to ensure proper memory release when using malloc(), free(), and realloc() functions to avoid memory leaks and dangling pointers.