释放内存为什么要用二级指针

malloc和free:

char * p = (char *)malloc(10);
free(p);

opencv中:

CvMat * mat = cvCreateMat(600, 800, CV_8UC3);
cvReleaseMat(&mat); // 这里为什么要用mat的地址,为什么不直接用mat
看了下源代码,是为了在内存释放后,把指针置空,core_c.h : 看了下源代码,是为了在内存释放后,把指针置空,core_c.h :
/* <free> wrapper.
   Here and further all the memory releasing functions
   (that all call cvFree) take double pointer in order to
   to clear pointer to the data after releasing it.
   Passing pointer to NULL pointer is Ok: nothing happens in this case
*/
CVAPI(void)   cvFree_( void* ptr );
#define cvFree(ptr) (cvFree_(*(ptr)), *(ptr)=0)

/* wrapper. Here and further all the memory releasing functions (that all call cvFree) take double pointer in order to to clear pointer to the data after releasing it. Passing pointer to NULL pointer is Ok: nothing happens in this case */ CVAPI(void) cvFree_( void* ptr ); #define cvFree(ptr) (cvFree_(*(ptr)), *(ptr)=0)
malloc和free: char * p = (char *)malloc(10); free(p); opencv中: CvMat * mat = cvCreateMat(600, 800, CV_8UC3); cvReleaseMat(&mat); // 这里为什么要用mat的地址,为什么不直接用mat 看了下源代码,是为了在内存释放后,把指针置空,core_c.h : /* wrapper. Here and further all the memory releasing functions (that all call cvFree) take double pointer in order to to clear pointer to the data after releasing it. Passing pointer to NULL pointer is Ok: nothing happens in this case */ CVAPI(void) cvFree_( void* ptr ); #define cvFree(ptr) (cvFree_(*(ptr)), *(ptr)=0)
经验分享 程序员 微信小程序 职场和发展