delete vs NULL vs free in c++

后端 未结 6 956
谎友^
谎友^ 2020-12-13 04:16

what is the difference between deleting a pointer, setting it to null, and freeing it.

delete ptr;

vs.

ptr=NULL;
         


        
6条回答
  •  眼角桃花
    2020-12-13 04:37

    delete will give allocated memory back to the C++ runtime library. You always need a matching new, which allocated the memory on the heap before. NULL is something completely different. A "placeholder" to signify that it points to no address. In C++, NULLis a MACRO defined as 0. So if don't like MACROS, using 0 directly is also possible. In C++0x nullptr is introduced and preferable.

    Example:

    int* a;        //declare pointer
    a = NULL;      //point 'a' to NULL to show that pointer is not yet initialized 
    a = new int;   //reserve memory on the heap for int
    
    //... do more stuff with 'a' and the memory it points to
    
    delete a;      //release memory
    a = NULL;      //(depending on your program), you now want to set the pointer back to
                   // 'NULL' to show, that a is not pointing to anything anymore
    

提交回复
热议问题