Problems with encapsulating the free function

Source: Internet
Author: User

[Cpp] When you are working on a single-chip microcomputer project, you need to encapsulate the free function of the C library, such as MMFree, so that you can add debugging information in it for output. But, alas, I think it's easy. I designed this: [cpp] void MXFreeP (void * p) {free (p); p = NULL;} int main (int argc, char ** argv) {char * p = NULL; p = (char *) malloc (1); if (NULL! = P) {* p = 0x05;} MXFreeP (p); if (NULL = p) {printf ("p = NULL \ n ");} else {printf ("p! = NULL \ n "); // after running, output this} system (" pause "); return 0 ;}result, the system crashed. After I came back, I wrote this on the PC. Although the program did not crash, the content pointed to by the pointer was not released. I think of the previous issue of using pointers as function parameters. Two-dimensional pointers are required. After modification: [cpp] void MXFreePP (void ** p) {free (* p); * p = NULL;} int main (int argc, char ** argv) {char * p = NULL; p = (char *) malloc (1); if (NULL! = P) {* p = 0x05;} MXFreePP (void **) & p); if (NULL = p) {printf ("p = NULL \ n"); // output this} else {printf ("p! = NULL \ n ");} system (" pause "); return 0;} finally got the expected result. However, to use this function, you must obtain a two-dimensional pointer. If it is obtained inside the function, and because it is a value copy, the obtained two-dimensional pointer is not the original two-dimensional pointer. I have been thinking for a long time. Use a macro. [Cpp] # define MXFreePP (p) free (void * (p); \ printf ("I have been freed. \ n ") the pointer to the C language is really profound, and I will continue to study

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.