0

I am trying to check the size of pointer memory allocated through malloc(). For this I write a program in which I initially allocate memory size of 10. Then insert a for loop and keep increasing memory by using realloc(). I am checking memory size by using sizeof.

Here is my code:

int main(int argc, _TCHAR* argv[])
{
    char *ptr;
    long int size;
    int count;

    ptr = (char *) malloc(10);
    size = sizeof(*ptr);
    printf("size of ptr is= %d\n",size);

    for(count=11;count<=100;count++)
    {
        ptr=(char *) realloc(ptr,count);
        size = sizeof(*ptr);
        printf("size of ptr is= %d\n",size);
    }

    return 0;
}

But I am getting always '1' as output:

enter image description here

So, please tell me if there is any other way to do this.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
Tabish Saifullah
  • 570
  • 1
  • 5
  • 25
  • 2
    This is a good indication that `sizeof` doesn't do what you think it does and that it's a good time to go find a reference on it. – chris Mar 07 '15 at 05:41
  • 1
    I don't understand, you allocate 10 items and want to know how many items you allocated? Why not save the quantity in a variable? – Thomas Matthews Mar 07 '15 at 05:59
  • "C/C++" is not a language. They are two different languages. Since you've only used C constructs in your code, I've taken the liberty of editing your question accordingly. In the future, please constrain your question to either one or the other. – Jonathon Reinhart Mar 07 '15 at 06:00

2 Answers2

8

ptr is of type char *, so sizeof(*ptr) is equivalent to sizeof(char), that's why you always get 1 in the output.

In general, there's no portable way to get the memory size from the pointer that malloc returns, you need to remember the size manually.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
0

Got my answer by my own. Here is the solution (step1) include header file "#include <malloc.h>" (step2) and use this line "size = _msize( ptr );" to get size

Tabish Saifullah
  • 570
  • 1
  • 5
  • 25
  • 3
    `_msize` is a Microsoft Visual C extension, and is not defined by ANSI C, POSIX, or any other spec adhered to by other compilers. *Don't use it*. It is *trivial* to remember the size of your allocation. – Jonathon Reinhart Mar 07 '15 at 05:57