Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate size of pointer pointed memory?

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?

like image 212
Jeegar Patel Avatar asked Jul 26 '11 11:07

Jeegar Patel


People also ask

How do you calculate the size of memory pointed by pointer?

If you allocated memory for a single value, you probably used sizeof() to find the amount of space needed for that value's type. You should know what that type was, too, because it's the type of the pointer. So you can just call sizeof() again on the same type.

What is the memory size of a pointer?

Pointers take up the space needed to hold an address, which is 4 bytes on a 32-bit machine and 8 bytes on a 64-bit machine.

How can you tell the size of memory allocated by malloc using pointers?

It is impossible to know how much memory was allocated by just the pointer. doing sizeof (p) will get the size of the pointer variable p which it takes at compile time, and which is the size of the pointer. That is, the memory the pointer variable takes to store the pointer variable p .


1 Answers

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 );
like image 153
unkulunkulu Avatar answered Sep 24 '22 01:09

unkulunkulu