Possible Duplicate:
How can I get the size of an array from a pointer in C?
How can I get the size of a memory block allocated using malloc()?
void func( int *p)
{
// Add code to print MEMORY SIZE which is pointed by pointer p.
}
int main()
{
int *p = (int *) malloc(10 * sizeof(int));
func(p);
}
How can we find MEMORY SIZE from memory pointer P in func() ?
You cannot do this in a portable manner in C. It may not be stored anywhere;
malloc()could reserve a region much larger than you asked for, and isn’t guaranteed to store any information about how much your requested.You either need to use a standard size, such as
malloc(ARRAY_LEN * sizeof(int))ormalloc(sizeof mystruct), or you need to pass the information around with the pointer: