How to calculate size of pointer pointed memory

cmemory-management

In one function I have written:

char *ab; 

ab=malloc(10);

Then in another function I want to know the size of memory pointed by the ab pointer.
Is there any way that I can know that ab is pointing to 10 chars of memory?

Best Answer

No, you don't have a standard way to do this. You have to pass the size of the pointed-to memory along with the pointer, it's a common solution.

I.e. instead of

void f(char* x)
{
    //...
}

use

void f(char *x, size_t length)
{
    //....
}

and in your code

 char *ab = malloc( 10 );
 f( ab, 10 );