Namespaces
Variants

Talk:c/language/sizeof

From cppreference.com

As per standard : "If the type of expression is a variable-length array type, expression is evaluated and the size of the array it evaluates to is calculated at run time." Also, "Note that if a has pointer type (such as after array-to-pointer conversion of function parameter type adjustment), this expression would simply divide the number of bytes in a pointer type by the number of bytes in the pointed type."

#include <stdio.h>
#include <stdlib.h>
 
int main (void)
{
        int n=2;
        int (*arr)[n] = NULL;
/*      if(arr[0] == NULL)
                printf("yes\n");
        else
                printf("no\n");
*/
        printf("%zu\n",sizeof arr[0]);
        return 0;    
}

Here, we have a variable-length array arr, therefore the size expression is evaluated but arr[0] is a null pointer, so during evaluation it should lead to undefined behaviour and output segmentation fault. But its not the case , program runs smoothly with an output of 8 bytes!! Himanshujha199640 (talk) 10:08, 17 August 2017 (PDT)

"runs smoothly" is just as valid as "segmentation fault" for a program whose behavior is undefined. FYI, dereferencing a null pointer directly also does not necessarily lead to a segmentation fault - compilers sometimes simply remove such code. --Cubbi (talk) 10:44, 17 August 2017 (PDT)

Too big VLAs

Is there a standard rule for sizeof on too big VLAs? E.g:

#include <stdio.h>
 
int main(void)
{
   size_t dim1, dim2;
   sscanf("1000000000000 100000", "%zX %zX", &dim1, &dim2);
   printf("%zu\n", sizeof(char[dim1][dim2]));
}

GCC and Clang seem to give 0 as a result if dim1 * dim2 is too big for size_t. Is it standard? (Or does the standard say something else?) This would be a way to know if we can allocate such an array with malloc or realloc, as described here.

2001:660:6101:800:202:0:0:3 02:16, 13 September 2023 (PDT)