Can “sizeof(arr[0])” lead to undefined behavior?

后端 未结 5 1403
长发绾君心
长发绾君心 2020-12-31 05:31

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

5条回答
  •  鱼传尺愫
    2020-12-31 05:58

    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.

提交回复
热议问题