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

后端 未结 5 1371
长发绾君心
长发绾君心 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:41

    In general case, if I'm missing something, dereferencing a null pointer under sizeof can lead to undefined behavior. Since C99, sizeof is not a purely compile time construct. The operand of sizeof is evaluated at run-time if the operand type is a VLA.

    Consider the following example

    unsigned n = 10;
    int (*a)[n] = NULL; // `a` is a pointer to a VLA 
    
    unsigned i = 0;
    sizeof a[i++];      // applying `sizeof` to a VLA
    

    According to the C99 standard, the argument of sizeof is supposed to be evaluated (i.e. i is supposed to get incremented). Yet I'm not entirely sure that the null-point dereference in a[0] is supposed to produce undefined behavior here.

提交回复
热议问题