14

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);
    }
}

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.

SGM1
  • 968
  • 2
  • 12
  • 23

2 Answers2

9

No, you can't.

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.

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.

Halim Qarroum
  • 13,985
  • 4
  • 46
  • 71
  • it also doesn't specify whether this dynamic memory is owned by you or somebody else. I'm wondering if there is a better name for "a pointer which is a resource specifically owned by this object, in contrast to a pointer managed by somebody else". – Dmytro Dec 09 '16 at 11:56
5

No way to check, you ought to NULL initialize and then test whether NULL indeed

From section 7.20.3.2 The free function of C99 standard:

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

kiriloff
  • 25,609
  • 37
  • 148
  • 229