There is a well known pattern of figuring out array length:
int arr[10];
size_t len = sizeof(arr) / sizeof(arr[0]);
assert(len == 10);
T
This will not cause undefined behavior.
With the exception of taking the size of variable-length arrays, sizeof
is a compile-time constant expression. The compiler processes the expression to determine its type, without producing the code to evaluate the expression at compile time. Therefore, the value at ptr[0]
(which is an uninitialized pointer) does not matter at all.
Moreover, if you would like to allocate ten integers, you should be calling malloc
like this:
int *ptr = malloc(known_len * sizeof(ptr[0]));
Otherwise, you allocate ten bytes, which is too small for storing ten integers. Note that in the expression above ptr
is uninitialized at the time of the call, which is perfectly fine for sizeof
.