且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以检查指针是否由malloc/calloc/realloc分配吗?

更新时间:2023-12-01 09:39:10

不,你不能.

基本上,您不需要这样做.如果您想编写一个辅助函数来释放给定指针的内存,那么您应该有意识地明确地将动态分配的指针传递给特定的内存区域以进行操作如此.

Basically, you should not need to do this. If you are wanting to write a helper function to free some memory given a pointer, than you should awarely and explicitely pass a dynamically allocated pointer to a certain area of memory to do so.

C中的原始指针不能传送有关它们指向的内存的额外信息.如果您希望获得此类信息,则必须传递一个附加包装器,该包装器包含您感兴趣的指针,例如:

Raw pointers in C cannot transport extra informations about the memory they are pointing to. If you want to have such informations, you will have to pass an additional wrapper that holds the pointer you are interested in, such as :

typedef struct my_pointer
{
   void  *ptr;
   int   is_dynamically_allocated;
}  ptr;

但这将是巨大的内存/时间损失.

But this would be a huge loss of memory/time.