Paul ha scritto:
I was asked such a question: how to determine the size of memory of
the int pointer pointed? for example
int GetTheSizeofMemory(int *buffer)
...
we can not use sizeof(buffer) to get the value, how should we do?
As others have already answered, you can't and one option is to write
your own malloc/free functions.
I've never really done it, but I've always thought that, in case I need
them, I would have implemented something like this:
void *mymalloc(size_t sz)
{
size_t *p;
p = malloc(sz + sizeof(size_t));
if (p) {
*p = sz;
return p + 1;
}
return NULL;
}
void myfree(void *p)
{
free(((size_t *)p)-1);
}
size_t myblocksize(void *p)
{
return ((size_t *)p)[-1];
}
I can imagine all weird things happening if pointers obtained with
malloc get passed to these functions, but avoiding to pass invalid
pointer to functions is among the first things a C programmer learns.
I understood that some malloc() implementation behaves this way, storing
the relevant information just before the pointer returned.
What I've never investigated is if there are issues with alignment,
portability or any other drawback I might have missed.
Remo.D