Memory learning (2) Introduction to memory overflow and solutions

1. Definition of memory overflow

It means that when the program applies for memory, there is not enough memory space for it to use, and out of memory appears, usually when a certain memory space is exhausted

Second, the cause of memory overflow

  1. The amount of data loaded in the memory is too large, such as assigning long type data to int integer variables
  2. There is an infinite loop in the code
  3. The memory allocation is not successful, but continues to be used, you can check whether the pointer is NULL before using the memory to judge
  4. The memory was allocated successfully, but it was referenced uninitialized
  5. The memory allocation is successful, there is a reference to the variable after initialization, and it is not released after use
  6. The memory allocation is successful. After initialization, the operand variable crosses the boundary of the memory

3. Some common memory overflow risks

3.1 strcpy function

Function prototype: char strcpy(char dest, const char *src);
Function function: Copy the string starting from src address and containing NULL terminator to dest address
Function description: The memory areas pointed to by src and dest cannot overlap; dest must have enough space to accommodate the string of src
Remarks : When the length of src is greater than the space allocated by dest, memory overflow will occur, and strncpy should be used to avoid

3.2 sprintf function

Function Prototype: int sprintf(char *buffer, const char *format, [argument]…);
Function Function: Format a string, write the formatted data into the string pointer buffer
Note: When the length of the written data is larger than the memory space of the buffer, it will cause memory overflow, and snprintf should be used as much as possible to avoid

3.3 malloc function

To use the malloc function, the memory space needs to be freed, and the original pointer variable must be assigned a NULL pointer. If you forget to assign NULL, the original pointer variable will become a wild pointer without a clear pointer, and the system does not know where it will point.

The calloc function does not need to be assigned NULL manually, because the system will automatically assign the original pointer to a null pointer every time the calloc function is called

Guess you like

Origin blog.csdn.net/future_sky_word/article/details/125830572