Using sizeof() on malloc'd memory

37,279

Solution 1

In C89, sizeof operator only finds the size of a variable in bytes at compile time (in this case a void pointer of 8 bytes). It works the way you'd expect it to work on plain arrays, because their size is known at compile time.

char arr[100]; // sizeof arr == 100
char *p = arr; // sizeof p == 4 (or 8 on 64-bit architectures)
char *p = malloc(100); // sizeof p == 4 (or 8). Still!

To know the size of heap-allocated memory, you need to keep track of it manually, sizeof won't help you.

Solution 2

sizeof returns the size of the pointer (void *) that you gave it, not the size of the memory you allocated. You would have to store the size of the memory in a separate variable if you want to use it later.

Solution 3

You cannot. As pointed out, you can get the size of the void * mallocated, but that does not tell you much.

You cannot get the size of the malloed *mallocated. That is to say, there is no function call to return 100 (in your example) - unless you write your own memory management routines.

Simplest is just to remember it somewhere ... maybe ....

stuct {
  void *data;
  unsigned int size
 } myStructureWhichRemebersItsSize;

myStructureWhichRemebersItsSize *someData;
someData.data = malloc(100);  // and check for NULL
someData.size = 100;
Share:
37,279
Michael Dickens
Author by

Michael Dickens

Updated on June 11, 2020

Comments

  • Michael Dickens
    Michael Dickens about 4 years

    Possible Duplicate:
    newbie questions about malloc and sizeof

    I am trying to read strings into a program. When I noticed that the strings were sometimes being corrupted, I tried the following code:

     void *mallocated = malloc(100);
     printf("sizeof(mallocated) = %d\n", sizeof(mallocated));
    

    According to my program, the size of mallocated was 8, even though I allocated 100 bytes for it. Because of this, whenever I try to store a string longer than 8 bytes, everything after the 8th byte will sometimes disappear. Why is this happening, and how can I prevent it?