A part of my main contains
int* p = NULL;
p = malloc(sizof(int)*10);
p = realloc(p, sizeof(int) * 5);
free(p);
Is there any way to find out if, after reallocation, the pointer p points to a memory block of size 20 bytes and not 40 bytes anymore?
The ideal would be to have a function that takes an address of memory as argument and tells if it's allocated or free. Is there such a function?
Another idea would be to check the size before and after the realloc() of the allocated memory. But I don't see how sizeof() could help, because how would I identify the block of memory, sizeof() sends the size of variables and not the size of a block of memory. sizeof(p) will give me 8 bytes, since p is a pointer and sizeof(*p) is 4, since p points to an integer.
Maybe there is a special use of sizeof() or some another function?
Read more if you want to know why I ask...
If I initialize my p to hold/point to an array
for (int i = 0; i < 3 ; i++){
p[i] = i;
}
I want now p to hold only {0,1,2} so I want to reallocate p from sizeof(int)* 5 to sizeof(int)*3.
But let's say I don't really know if p should be reallocated, the memory block is 20 bytes, but maybe it's already 12 bytes, and realloc() is not needed. I know I can run realloc() either way and it won't hurt, so maybe it's not really a good reason for this question. But in a longer code it's easy to lose track of the amount of allocated memory.
Any help will be much appreciated.
PS: if no one answers I will have to get satisfaction from valgrind sending 0 errors.
After all, if something is wrong, for example writing in 21st, 22nd, 23rd and 24th bytes of memory (ex: p[4] = 7) of a block of 20 bytes (because p = realloc(p, sizeof(int) * 5)) valgrind sends errors of type "invalid write of size 4", but to get that I need to write in this memory. This method of verification makes me want to get errors, because if I can accurately predict an error then I know the actual size of the allocated memory.