Today, I saw a question on the Internet, "Suppose malloc has a string of memory." Then, it changes the size of the string and asks if there is a part of the memory that is not released. "This question was never carefully thought of.
Of course. I think it's definitely going to be released, but I've never understood the principle of free. Dare not utter nonsense.
I looked at the memory management of the operating system. Basically this, of course, the implementation of each system is different.
The operating system manages memory, maintains a spare memory chain list, and malloc chooses one from a list to use. Each memory block has a header that represents the basic information of the memory, such as the size of the memory.
So free can remember the memory size that the original pointer refers to, rather than using a memory block to temporarily calculate the size of the memory point, not the method of calculating the length of the string is misleading.
Another point to note is that when the system is in free memory, it remembers only the address of malloc and the size of the allocated memory.
For example, char *p = (char *) malloc (10); The allocation of 10 bytes is generated. Suppose you change the address of the pointer to P = p + 1; Then free is going to be a problem. The program will crash.
Assume that you must change the value of the pointer. It is recommended to do this char *NEWP = p; Then change NEWP = Newp + 1. Last free (p);
Another point to note. A string of length 10 takes 11 bytes. Because of another ' lenght ', allocate memory to allocate the size of the 1 +.
The principle of the C language free function —————————— "Badboy"