0

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?

1
  • How do you initialize your array? Commented Feb 2, 2015 at 4:11

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Instead of passing size, you could also consider null terminating the list since its an array of pointers =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.