Summary of C language memory related programming skills

1. Introduction

This article mainly introduces the programming experience and skills related to C language memory, which is divided into three parts: allocating memory, using memory and releasing memory, for the reference of relevant developers.

2. Experience summary content

2.1 Allocate memory

2.1.1 When allocating module memory, it is best to achieve 8-byte alignment

Because it is more efficient to access memory on different platforms. Even on some platforms, problems may occur if the memory is not 8-byte aligned.

2.2.2 Use custom malloc function

When allocating memory, use the custom malloc function and add flag bytes such as 0x5A5A before and after allocating the memory. In this way, if the flag bit of this memory is modified out of bounds, it can be determined when it is released and an error will be reported. It will not lead to more serious crashes.

2.2 Using memory

2.2.1 Simulation debugging to confirm memory address and offset

After allocating memory for each module of the algorithm, during simulation debugging, print out the memory address and allocation size, and calculate whether the corresponding address and offset are correct to ensure that there will be no crash problems caused by inconsistent memory offsets and expectations.

2.3 Release memory

2.3.1 The pointer needs to be empty after releasing the memory

After the memory is released, the location pointed by the pointer is still the address of the original memory, but at this time the memory at the corresponding address can no longer be used. So the pointer needs to be set to NULL. The advantage of this is: the next time the pointer is used, if a non-null judgment is made, an error will be reported directly, otherwise it will cause a wild pointer access and crash.

Three, summary

This article mainly introduces some programming skills related to C language memory. It is being continuously updated for reference by relevant developers. Everyone is welcome to discuss and exchange together~

Guess you like

Origin blog.csdn.net/xuxu_123_/article/details/134988404