How can I get the size of an array from a pointer in C?

Viewed 46703

I've allocated an "array" of mystruct of size n like this:

if (NULL == (p = calloc(sizeof(struct mystruct) * n,1))) {
 /* handle error */
}

Later on, I only have access to p, and no longer have n. Is there a way to determine the length of the array given just the pointer p?

I figure it must be possible, since free(p) does just that. I know malloc() keeps track of how much memory it has allocated, and that's why it knows the length; perhaps there is a way to query for this information? Something like...

int length = askMallocLibraryHowMuchMemoryWasAlloced(p) / sizeof(mystruct)

I know I should just rework the code so that I know n, but I'd rather not if possible. Any ideas?

16 Answers

No, there is no way to get this information without depending strongly on the implementation details of malloc. In particular, malloc may allocate more bytes than you request (e.g. for efficiency in a particular memory architecture). It would be much better to redesign your code so that you keep track of n explicitly. The alternative is at least as much redesign and a much more dangerous approach (given that it's non-standard, abuses the semantics of pointers, and will be a maintenance nightmare for those that come after you): store the lengthn at the malloc'd address, followed by the array. Allocation would then be:

void *p = calloc(sizeof(struct mystruct) * n + sizeof(unsigned long int),1));
*((unsigned long int*)p) = n;

n is now stored at *((unsigned long int*)p) and the start of your array is now

void *arr = p+sizeof(unsigned long int);

Edit: Just to play devil's advocate... I know that these "solutions" all require redesigns, but let's play it out. Of course, the solution presented above is just a hacky implementation of a (well-packed) struct. You might as well define:

typedef struct { 
  unsigned int n;
  void *arr;
} arrInfo;

and pass around arrInfos rather than raw pointers.

Now we're cooking. But as long as you're redesigning, why stop here? What you really want is an abstract data type (ADT). Any introductory text for an algorithms and data structures class would do it. An ADT defines the public interface of a data type but hides the implementation of that data type. Thus, publicly an ADT for an array might look like

typedef void* arrayInfo;
(arrayInfo)newArrayInfo(unsignd int n, unsigned int itemSize);
(void)deleteArrayInfo(arrayInfo);
(unsigned int)arrayLength(arrayInfo);
(void*)arrayPtr(arrayInfo);
...

In other words, an ADT is a form of data and behavior encapsulation... in other words, it's about as close as you can get to Object-Oriented Programming using straight C. Unless you're stuck on a platform that doesn't have a C++ compiler, you might as well go whole hog and just use an STL std::vector.

There, we've taken a simple question about C and ended up at C++. God help us all.

keep track of the array size yourself; free uses the malloc chain to free the block that was allocated, which does not necessarily have the same size as the array you requested

Just to confirm the previous answers: There is no way to know, just by studying a pointer, how much memory was allocated by a malloc which returned this pointer.

What if it worked?

One example of why this is not possible. Let's imagine the code with an hypothetic function called get_size(void *) which returns the memory allocated for a pointer:

typedef struct MyStructTag
{ /* etc. */ } MyStruct ;

void doSomething(MyStruct * p)
{
   /* well... extract the memory allocated? */
   size_t i = get_size(p) ;
   initializeMyStructArray(p, i) ;
}

void doSomethingElse()
{
   MyStruct * s = malloc(sizeof(MyStruct) * 10) ; /* Allocate 10 items */
   doSomething(s) ;
}

Why even if it worked, it would not work anyway?

But the problem of this approach is that, in C, you can play with pointer arithmetics. Let's rewrite doSomethingElse():

void doSomethingElse()
{
   MyStruct * s = malloc(sizeof(MyStruct) * 10) ; /* Allocate 10 items */
   MyStruct * s2 = s + 5 ; /* s2 points to the 5th item */
   doSomething(s2) ; /* Oops */
}

How get_size is supposed to work, as you sent the function a valid pointer, but not the one returned by malloc. And even if get_size went through all the trouble to find the size (i.e. in an inefficient way), it would return, in this case, a value that would be wrong in your context.

Conclusion

There are always ways to avoid this problem, and in C, you can always write your own allocator, but again, it is perhaps too much trouble when all you need is to remember how much memory was allocated.

Some compilers provide msize() or similar functions (_msize() etc), that let you do exactly that

May I recommend a terrible way to do it?

Allocate all your arrays as follows:

void *blockOfMem = malloc(sizeof(mystruct)*n + sizeof(int));

((int *)blockofMem)[0] = n;
mystruct *structs = (mystruct *)(((int *)blockOfMem) + 1);

Then you can always cast your arrays to int * and access the -1st element.

Be sure to free that pointer, and not the array pointer itself!

Also, this will likely cause terrible bugs that will leave you tearing your hair out. Maybe you can wrap the alloc funcs in API calls or something.

malloc will return a block of memory at least as big as you requested, but possibly bigger. So even if you could query the block size, this would not reliably give you your array size. So you'll just have to modify your code to keep track of it yourself.

For an array of pointers you can use a NULL-terminated array. The length can then determinate like it is done with strings. In your example you can maybe use an structure attribute to mark then end. Of course that depends if there is a member that cannot be NULL. So lets say you have an attribute name, that needs to be set for every struct in your array you can then query the size by:


int size;
struct mystruct *cur;

for (cur = myarray; cur->name != NULL; cur++)
    ;

size = cur - myarray;

Btw it should be calloc(n, sizeof(struct mystruct)) in your example.

Other have discussed the limits of plain c pointers and the stdlib.h implementations of malloc(). Some implementations provide extensions which return the allocated block size which may be larger than the requested size.

If you must have this behavior you can use or write a specialized memory allocator. This simplest thing to do would be implementing a wrapper around the stdlib.h functions. Some thing like:

void* my_malloc(size_t s);     /* Calls malloc(s), and if successful stores 
                                  (p,s) in a list of handled blocks */
void my_free(void* p);         /* Removes list entry and calls free(p) */
size_t my_block_size(void* p); /* Looks up p, and returns the stored size */
...

I'm not aware of a way, but I would imagine it would deal with mucking around in malloc's internals which is generally a very, very bad idea.

Why is it that you can't store the size of memory you allocated?

EDIT: If you know that you should rework the code so you know n, well, do it. Yes it might be quick and easy to try to poll malloc but knowing n for sure would minimize confusion and strengthen the design.

One of the reasons that you can't ask the malloc library how big a block is, is that the allocator will usually round up the size of your request to meet some minimum granularity requirement (for example, 16 bytes). So if you ask for 5 bytes, you'll get a block of size 16 back. If you were to take 16 and divide by 5, you would get three elements when you really only allocated one. It would take extra space for the malloc library to keep track of how many bytes you asked for in the first place, so it's best for you to keep track of that yourself.

malloc() stores metadata regarding space allocation before 8 bytes from space actually allocated. This could be used to determine space of buffer. And on my x86-64 this always return multiple of 16. So if allocated space is multiple of 16 (which is in most cases) then this could be used:

Code

#include <stdio.h>
#include <malloc.h>

int size_of_buff(void *buff) {
        return ( *( ( int * ) buff - 2 ) - 17 ); // 32 bit system: ( *( ( int * ) buff - 1 ) - 17 )
}

void main() {
        char *buff = malloc(1024);
        printf("Size of Buffer: %d\n", size_of_buff(buff));
}

Output

Size of Buffer: 1024

This is my approach:

#include <stdio.h>
#include <stdlib.h>

typedef struct _int_array
{
    int *number;
    int size;
} int_array;

int int_array_append(int_array *a, int n)
{
    static char c = 0;
    if(!c)
    {
        a->number = NULL;
        a->size = 0;
        c++;
    }

    int *more_numbers = NULL;

    a->size++;
    more_numbers = (int *)realloc(a->number, a->size * sizeof(int));
    if(more_numbers != NULL)
    {
        a->number = more_numbers;
        a->number[a->size - 1] = n;
    }
    else
    {
        free(a->number);
        printf("Error (re)allocating memory.\n");
        return 1;
    }

    return 0;
}

int main()
{
    int_array a;

    int_array_append(&a, 10);
    int_array_append(&a, 20);
    int_array_append(&a, 30);
    int_array_append(&a, 40);

    int i;
    for(i = 0; i < a.size; i++)
        printf("%d\n", a.number[i]);

    printf("\nLen: %d\nSize: %d\n", a.size, a.size * sizeof(int));

    free(a.number);
    return 0;
}

Output:

10
20
30
40

Len: 4
Size: 16

If your compiler supports VLA (variable length array), you can embed the array length into the pointer type.

int n = 10;
int (*p)[n] = malloc(n * sizeof(int));
n = 3;
printf("%d\n", sizeof(*p)/sizeof(**p));

The output is 10.

You could also choose to embed the information into the allocated memory yourself with a structure including a flexible array member.

struct myarray {
    int n;
    struct mystruct a[];
};

struct myarray *ma =
    malloc(sizeof(*ma) + n * sizeof(struct mystruct));
ma->n = n;
struct mystruct *p = ma->a;

Then to recover the size, you would subtract the offset of the flexible member.

int get_size (struct mystruct *p) {
    struct myarray *ma;
    char *x = (char *)p;
    ma = (void *)(x - offsetof(struct myarray, a));
    return ma->n;
}

The problem with trying to peek into heap structures is that the layout might change from platform to platform or from release to release, and so the information may not be reliably obtainable.

Even if you knew exactly how to peek into the meta information maintained by your allocator, the information stored there may have nothing to do with the size of the array. The allocator simply returned memory that could be used to fit the requested size, but the actual size of the memory may be larger (perhaps even much larger) than the requested amount.

The only reliable way to know the information is to find a way to track it yourself.

Related