The malloc () function in C language is used to dynamically allocate a space in the memory to store data. It is very useful for applications that need to dynamically allocate memory during program execution.
The Microchip compiler C30 (16-Bit Microcontroller) and C32 (32-Bit Microcontroller) also began to implement this function in a newer version, this adds a lot of flexibility to the programming of a single-chip microcomputer with some limitations on RAM. However, there are several precautions during actual use (take MPLab v8.63 as an example ).
1. You need to inform the compiler program that dynamic memory allocation will be used. Otherwise, the compilation in the 16-Bit Microcontroller will fail, and the compilation in the 32-Bit Microcontroller will not fail, but when the program is running, malloc allocation will fail.
The options are located in the Project-> Build Option-> MPLab xx Link Interface, find the Heap Size box, and enter the number of bytes that may be required to dynamically allocate. In addition, it is noted that the size of the input bytes cannot be fully allocated during the running of the program, the maximum number of bytes actually can be obtained is 8 bytes less than the number of input bytes. Otherwise, malloc returns NULL, indicating that space allocation fails. I don't know whether this is a bug in the compiler or the natural loss in the space allocation process.
2. Before the program allocates a large space for the first time, it needs to "warm up", that is, pre-allocate a small space to obtain the maximum space set during setup.
For example, if the heap space is set to 16384 bytes (byte), the malloc function is used to request the allocation of such a large amount of space when running. If malloc returns NULL, the allocation fails. By repeatedly trying to find that you need to malloc even one byte space before allocating large space, and then release it with free, and then use malloc to request large space, there will be no problem. In addition, the "big" space must be greater than 1/2 of the heap space input value. For example, if the program sends a request to allocate less than 16384 of the space, there is no need to "push the body.