Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the size of dynamically allocated array in C [duplicate]

I know that this question has been asked before, but my question is more specific, here is the code:

#include <stdio.h>
#include <time.h>    /* must be included for the time function */

main()
{
    time_t t = time(NULL);
    srand((unsigned) t);

    int i = rand();

    int a[i];

    printf("%d\n", i);        /* ouptut: 18659 */
    printf("%d\n", sizeof a); /* output: 74636 */
}

I compiled this code using gcc and -ansi option to restrict it to recognize the ANSI C only. I know that there is no way that the compiler could know at compile-time the size of the array because it's determined randomly at run-time. Now my question is is the value returned by sizeof is just a random value, or it has a meaning?

like image 540
Maykel Jakson Avatar asked Dec 10 '22 11:12

Maykel Jakson


2 Answers

The sizeof operator is evaluated at compile time for most operands. In the case of a VLA, it is evaluated at runtime.

From section 6.5.3.4 of the C standard:

2 The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant

So the size returned by sizeof is the size in bytes of the VLA. In your example, that would be i * sizeof(int)

like image 172
dbush Avatar answered Dec 27 '22 20:12

dbush


The value returned by sizeof is a pseudo-random value that has a meaning:

  • The value represents the size of VLA a, in bytes
  • It is random only in the sense that the number of array elements is determined by a call to rand.

It appears that sizeof(int) on your system is 4, because the number returned by sizeof is four times the number of elements in the array.

Note: One of the consequences of allowing VLAs in C99 is that sizeof is no longer a purely compile-time expression. When the argument of sizeof operator is a VLA, the result is computed at run-time.

like image 23
Sergey Kalinichenko Avatar answered Dec 27 '22 20:12

Sergey Kalinichenko