0

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() ?

Community
  • 1
  • 1
siddharth
  • 579
  • 1
  • 8
  • 18

2 Answers2

2

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)) or malloc(sizeof mystruct), or you need to pass the information around with the pointer:

struct integers {
    size_t count;
    int *p;
};

void fun(integers ints) {
    // use ints.count to find out how many items we have
}

int main() {
    struct integers ints;
    ints.count = 10;
    ints.p = malloc(ints.count * sizeof(int));
    fun(ints);
}
Brian Campbell
  • 322,767
  • 57
  • 360
  • 340
0

There is no inbuilt logic to find the memory allocated for a pointer. you have to implement your own method for doing it as brian mentioned in his answer.

And yes,you can find the memory leaked using some tools like valgrind on linux. and on solaris there is a library libumem.so which has a function called findleaks which will tell you how much memory is leaked while the process is in running state.

Vijay
  • 65,327
  • 90
  • 227
  • 319