我可以检查指针是否由malloc/calloc/realloc分配吗? [英] Can I check if a pointer was allocated by malloc/calloc/realloc?

查看:95
本文介绍了我可以检查指针是否由malloc/calloc/realloc分配吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以检查传递给函数的指针是否由malloc/calloc/realloc分配?

I was wondering is it possible to check if a pointer passed into a function was allocated by malloc/calloc/realloc?

int main(){
    struct something o;
    struct something *a;
    a = malloc(sizeof(struct something));
    freeSome(&o);/*This would normally throw an (corruption?) error*/
    freeSome(a);/*This is fine*/
}

void freeSome(struct something * t){
    if (/*expression here*/){
        free(t);
    }
}

我知道通常您会检查是否为t == NULL,但是我只是想知道是否有可能查看是否已为给定指针分配了内存.

I understand that usually you check to see if t == NULL, but I was just wondering if it was possible to see if memory has been allocated for the given pointer.

推荐答案

不,你不能.

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

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.

这篇关于我可以检查指针是否由malloc/calloc/realloc分配吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆