The principle of the C language free function ———— "Badboy"

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.