Ankit Raizada wrote on 03/08/05 :
Is there a way to know how much memory has being allocated(dynamically)
to a pointer.
There is no 'memory allocated to a pointer'. This is misleading. All we
can have ia s a pointer containing anadress that can be the one of an
allocated block of memory.
If the only information we have is the address, there is no way to get
the size of the block. In most cases, you don't need it if the pointer
holding the address is correctly typed.
2 exceptions
- the pointer has the type void. No information about the size is
available at all.
- the pointer is typed, but the bloc is an array of this type. You know
the size of the first element (sizof *p), but you have no way to get
the number of elements.
This is why such a structure is recommended to hold allocated block
information.
struct allocated_T
{
size_t number_of_elements;
T *block_address;
};
or the generic way:
struct allocated
{
size_t size_of an_element;
size_t number_of_elements;
void *block_address;
};
Related to this, can we find out has a pointer already
been freed? I am using VC++
No. The Good Usage Rules recommend tu set the pointer to NULL after a
free()
free(p), p = NULL;
or some macro (yes, double evaluation, I know)
but it doesn't solve the alias problem. (The solution: don't alias
pointers...)
T *pa = malloc(...);
<...>
send_and_forget(pa), pa = NULL;
--
Emmanuel
The C-FAQ:
http://www.eskimo.com/~scs/C-faq/faq.html
The C-library:
http://www.dinkumware.com/refxc.html
..sig under repair