如何检查指针是否已在C中释放?
问题描述:
我想检查指针是否已经释放.如何使用gnu编译器集执行此操作?
I would like to check if a pointer is freed already or not. How do I do this using gnu compiler set?
答
您不能.跟踪它的方法是在释放指针后将其分配给0
或NULL
.但是,正如弗雷德·拉尔森(Fred Larson)所述,这对指向同一位置的其他指针没有任何作用.
You can't. The way to track this would be to assign the pointer to 0
or NULL
after freeing it. However as Fred Larson mentioned, this does nothing to other pointers pointing to the same location.
int* ptr = (int*)malloc(sizeof(int));
free(ptr);
ptr = NULL;