Reputation: 9437
Let's say I have a dynamically allocated array of structs of which I do not know the size, we'll call it *people. Now, I'm asked to check if this array has at least 12 elements, or structs, within it. Because it is dynamically allocated, I know sizeof() will not work, but what happens if I do something like the following?
int count = 0;
for (int i = 0; i <= 12; i++) {
if (people[i] == NULL) { <----- will this work?
exit(1);
}
count++;
}
printf("array has 12 or more elements");
Basically, my question is, would people[i] return NULL if the index, i, is greater than the size of the dynamically allocated array? If not, how would one go about checking if the array size is greater than a certain number (in this case 12)?
Upvotes: 1
Views: 1035
Reputation: 1
You should keep somewhere the run-time dimension of a heap-allocated array (e.g. allocated with calloc
or malloc
). You might consider using flexible array members like here to keep together the dimension and the data.
If you overflow your array, it is undefined behavior (see this answer). Beware of buffer overflows.
If on Linux, use valgrind after having compiled with all warnings & debug info (e.g. gcc -Wall -Wextra -g
). See also the -fsanitize
options of recent GCC & Clang/LLVM compilers.
Upvotes: 3
Reputation:
It doesn't work. You just run off the end of the allocated space and read memory which does not belong to the array and may contain any elements at all. That memory may start with a particular values, but all things considered this is rather unlikely, and in any case nothing you can count on. Just remember the size, in a second variable or in an associated struct
attribute.
Upvotes: 2