Further discussion on applying for 0-byte memory using the malloc function -- C language deep anatomy note

Source: Internet
Author: User
Environment: vs2008 for two times: malloc and free: malloc, free will leak memory at one time, no phenomenon at that time, but the machine will get slower and slower; malloc once, free twice will certainly make an error. In addition, null can be free for countless times. As for why, I think free is meaningless for null, so it doesn't matter if free is not free. If I want to design a free function, we can also design it like this so that those who suffer from such problems will be entangled.

Deep anatomy of C language p124

"Another question is: Will a null pointer be returned when I use the malloc function to apply for a 0-byte memory? You can test it or find instructions on the malloc function. To apply for a 0-byte memory, the function does not return NULL, but returns a normal memory address. However No Use the memory with a size of 0. This is like a scale on a ruler. the scale itself has no length. Only one or two pieces can be used together to determine the length. Be careful with this 1.1, because at this time if (null! = P) Statement validation will not work. "It is not unusable, but not usable. (It seems like it's almost so good) You can store data to this address, however, it may be overwritten if other memory allocation statements are allocated to other variables.
 
Char * CP = (char *) malloc (0); * CP = 'q'; // CP = 0x0039210, And the 'q' is saved, the ASCII value is 0x71.
After the experiment, when you apply for a memory of 0 and do not store data, it is no problem to free it;
 
Char * CP = (char *) malloc (0); free (CP );
When you save a data record and free the pointer, an error is returned ~~~
 
Char * CP = (char *) malloc (0); * CP = 'q'; // CP = 0x0039210. Why does vs2008 score this? Isn't it random in the stack? It seems that the compiler is not set to random during design. Free (CP); // it is best not to be okay to challenge the compiler's IQ

Related Article

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.