user3813674
user3813674

Reputation: 2673

Determining end of dynamic array in C

I have a user-defined struct call MyStruct and allocate a 2D dynamic array:

MyStruct** arr = (MyStruct**) malloc(sizeof(myStruct*)*size);

I want to process the array in a function:

void compute(MyStruct** lst)
{
    int index = 0;
    while(lst[index] != NULL)
    {  
        //do something
        index++;
    }
}

I called compute(arr) and it works fine. But valgrind complains that there is an invalid read of size sizeof(MyStruct) at line while(...). I understand that at this point index is out of bound by 1 element. An easy fix is to pass size to the function and check if index < size through the loop.

Out of curiosity, is there anyway I can still traverse through the array without indexing that extra element AND not passing size to the function?

Upvotes: 0

Views: 1589

Answers (1)

icktoofay
icktoofay

Reputation: 128993

There is no standard way, no.

That said, there may be some nonstandard ways you can get the allocated size of a malloced piece of memory. For example, my machine has a size_t malloc_size(const void *); function in <malloc/malloc.h>; glibc has a malloc_usable_size function with a similar signature; and Microsoft’s libc implementation has an _msize function, also with a similar signature.

These cannot simply be dropped in, though; besides the obvious portability concerns, these return the actual amount of memory allocated for you, which might be slightly more than you requested. That might be okay for some applications, but perhaps not for iterating through your array.

You probably ought to just pass the size as a second parameter. Boring, I know.

Upvotes: 4

Related Questions