Today, I saw a question on the Internet, "if 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 has not been carefully thought of before."
Of course, I think it will be released, but I have never known the principle of free, dare not say nonsense. I looked at the operating system memory management, basically this, of course, the implementation of the various systems are different.
The operating system manages memory, maintains an idle memory chain list, and malloc chooses one from a list to use, each memory block has a header to represent the basic information of this memory, such as memory size,
So free can remember the size of the memory that the original pointer refers to, rather than using a memory block to temporarily calculate the size of the memory, not the method of calculating the length of the string is misleading.
It is also important to note that when the system is in free memory, it remembers only the address of malloc, and the size of the allocated memory.
such as char *p = (char *) malloc (10); The allocation of 10 bytes is generated. If you change the address of the pointer to P = p + 1; Then free is going to be a problem. The program will crash.
If you must change the value of the pointer, it is recommended to do so char *NEWP = p; Then change NEWP = Newp + 1, last free (p);
It is also important to note that a string of length 10 takes up to 11 bytes. Because there is a ' lenght ', allocate the memory to allocate the size of the 1.