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.
It is impossible to know how much memory was allocated by just the pointer. doing sizeof (p) will get the size of the pointer variable p which it takes at compile time, and which is the size of the pointer. That is, the memory the pointer variable takes to store the pointer variable p .
No. Memory allocated by malloc is not deallocated at the end of a function. Otherwise, that would be a disaster, because you would be unable to write a function that creates a data structure by allocating memory for it, filling it with data, and returning it to the caller.
C realloc() method “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With