C Memory Management

This chapter explains dynamic memory management in C. The C language provides several functions for memory allocation and management. These functions can be<stdlib.h>Found in the header file.

In C language, memory is managed through pointer variables. A pointer is a variable that stores a memory address, which can point to variables of any data type, including integers, floating-point numbers, characters, arrays, and so on. C language provides some functions and operators that allow programmers to operate on memory, including allocation, deallocation, moving, and copying.

Serial NumberFunctions and Descriptions
1void *calloc(int num, int size);
Dynamically allocate num contiguous spaces of length size in memory, and initialize every byte to 0. So the result is that it allocates a memory space of num*size bytes in length, and the value of each byte is 0.
2void free(void *address);
This function releases the memory block pointed to by address; what is released is the dynamically allocated memory space.
3void *malloc(int num);
Allocates a memory space of a specified size in the heap area to store data. This memory space will not be initialized after the function execution completes, and their values are unknown.
4void *realloc(void *address, int newsize);
This function reallocates memory, extending the memory tonewsize。

Note:The void * type represents a pointer of an undetermined type. C and C++ stipulate that a void * type can be forcibly converted to a pointer of any other type through type casting.


Dynamically allocate memory

When programming, if you know the size of an array in advance, it is relatively easy to define the array. For example, an array that stores a person's name can hold up to 100 characters, so you can define the array as follows:

char name[100];

However, if you do not know in advance the length of the text you need to store, for example, you want to store a detailed description of a topic. Here, we need to define a pointer that points to characters whose required memory size is not defined, and then allocate memory later according to the needs, as shown below:

Example

#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[100]; char *description; strcpy(name, "Zara Ali"); /*Dynamic memory allocation*/ description = (char *)malloc( 200 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory\n"); } else { strcpy( description, "Zara ali a DPS student in class 10th"); } printf("Name = %s\n", name ); printf("Description: %s\n", description ); }

When the above code is compiled and executed, it produces the following results:

Name = Zara Ali
Description: Zara ali a DPS student in class 10th

The above program can also usecalloc()To write it, you only need to replace malloc with calloc, as follows:

calloc(200, sizeof(char));

When dynamically allocating memory, you have complete control and can pass a value of any size. Arrays with a predefined size, once defined, cannot change their size.

Resizing memory and freeing memory

When the program exits, the operating system will automatically release all memory allocated to the program. However, it is recommended that whenever you no longer need memory, you should call the functionfree()To free memory.

Alternatively, you can call the functionrealloc()to increase or decrease the size of an allocated memory block. Let's look at the above example again using the realloc() and free() functions:

Example

#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[100]; char *description; strcpy(name, "Zara Ali"); /*Dynamic memory allocation*/ description = (char *)malloc( 30 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory\n"); } else { strcpy( description, "Zara ali a DPS student."); } /*Suppose you want to store larger descriptive information*/ description = (char *) realloc( description, 100 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory\n"); } else { strcat( description, "She is in class 10th"); } printf("Name = %s\n", name ); printf("Description: %s\n", description ); /*Use the free() function to release memory*/ free(description); }

When the above code is compiled and executed, it produces the following results:

Name = Zara Ali
Description: Zara ali a DPS student.She is in class 10th

You can try not reallocating extra memory; the strcat() function will generate an error because there is not enough memory available for storing description.

Commonly used memory management functions and operators in the C language

  • malloc() function: used to dynamically allocate memory. It accepts one parameter, namely the size of memory to be allocated (in bytes), and returns a pointer to the allocated memory.

  • free() function: used to release previously allocated memory. It takes a pointer to the memory to be freed as a parameter and marks that memory as unused.

  • calloc() function: used to dynamically allocate memory and initialize it to zero. It accepts two parameters, namely the number of memory blocks to allocate and the size of each memory block (in bytes), and returns a pointer to the allocated memory.

  • realloc() function: used to reallocate memory. It accepts two parameters: a previously allocated pointer and a new memory size, then tries to resize the previously allocated memory block. If resizing succeeds, it returns a pointer to the reallocated memory; otherwise, it returns a null pointer.

  • sizeof operator: used to obtain the size of a data type or variable (in bytes).

  • Pointer operator: used to obtain the memory address pointed to by a pointer or the value of a variable.

  • & operator: used to obtain the memory address of a variable.

  • *Operator: used to obtain the value of the variable pointed to by a pointer.

  • -> Operator: used for pointers to access structure members, with the syntaxpointer->member, equivalent to(*pointer).member。

  • memcpy() function: used to copy data from a source memory area to a destination memory area. It accepts three parameters: a pointer to the destination memory area, a pointer to the source memory area, and the size of the data to be copied (in bytes).

  • memmove() function: similar to the memcpy() function, but it can handle overlapping memory areas. It accepts three parameters: a pointer to the destination memory area, a pointer to the source memory area, and the size of the data to be copied (in bytes).

other extensions