skip to Main Content

When executing this C code:

double *t = (double*) malloc(10 * sizeof(double));

printf("%lun", sizeof(t)/sizeof(t[0]);

for (int j = 0; j < 10; j++) {
   t[j] = 5 * powl((j/10), 0.4);            
   printf("t_j: %lfn", t[j]);           
}

My array has only 0 stored and the size of my array is 1.

I am using Xcode. With thread sanitiser turned on I get an error that malloc can’t allocate memory in vm-space.

malloc: nano zone abandoned due to inability to preallocate reserved vm space.

3

Answers


  1. sizeof on a pointer returns the size of the pointer, not the pointed to data.

    The sizeof trick would only work with an array.

    Note that sizeof returns size_t, not an unsigned long. The correct format specifier is %zu.

    There’s no way to get the number of elements a pointer is pointing to. You have keep track of the size yourself.

    size_t size = 10;
    

    Another approach would be to define it as an array:

    double array[10];
    

    And now the sizeof idiom would work.

    t[j] = 5 * powl((j/10), 0.4);
    

    This expression is always equal to 0 due to the integer arithmetic.
    You should write ( j / 10.0 ) – Vlad from Moscow

    The cast is not required. It only serves to clutter one’s code. malloc(3) returns NULL to indicate failure, leaving it unchecked risks invoking undefined behaviour.

    Login or Signup to reply.
  2. sizeof is giving you the size of the object. In your case sizeof(t) is giving the size of the pointere

    To see the size of the array you need to define it as an array

    double t[10];
    
    printf("%zun", sizeof(t)/sizeof(t[0]);
    
    Login or Signup to reply.
  3. The variable t is declared as a pointer of the type double *.

    So the expression sizeof(t)/sizeof(t[0]) is equivalent to sizeof( double * ) / sizeof( double ) and does not yield the number of elements in the allocated array.

    Also in this statement

    printf("%lun", sizeof(t)/sizeof(t[0]);
    

    there is a typo. You need to add one more closing parenthesis.

    And though the type size_t usually is defined as an alias for the type unsigned long it is more correctly to use the conversion specifier %zu instead of %lu because the C Standard allows in some implementations to define it as an alias for the type unsigned long long.

    Also in this expression (j/10) there is used the integer arithmetic. So it always evaluates to 0. You should write (j/ 10.0) to convert operands of the expression to the common type double.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search