:: Re: [DNG] simple-netaid from scratc…
Top Page
Delete this message
Reply to this message
Author: Didier Kryn
Date:  
To: dng
New-Topics: Re: [DNG] semantic of sizeof operator in C (was: simple-netaid from scratch)
Subject: Re: [DNG] simple-netaid from scratch
Le 12/06/2019 à 11:17, aitor a écrit :
> Hi Didier,
>
> En 12 de junio de 2019 7:40:08 Didier Kryn <kryn@???> escribió:
>>
>>>
>>>
>>>
>>>
>>> sizeof() is not a real function. Its syntax makes it look like a
>>> function but it is not. Its argument can be either a variable or a type
>>> (which no function can have). It is evaluated at compile time -
>>> which is
>>> equivalent to replacing it with the litteral value.
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> Didier
>>
>> But, in this concrete case, the size can be evaluated at compile time
>> because the memory is asigned statically by using a char array
>> (instead of a char* pointer). In the case of a dinamic memory
>> asignment (runtime), the size would be the value of the N variable
>> used in the malloc function.
>>
>> BTW, i recently added the systray icon to simple-netaid:
>>
>> https://git.devuan.org/aitor_czr/simple-netaid/blob/master/screenshots/systray-icon.png
>


    What I meant in this discussion is that sizeof() allows to
calculate the number of elements of an array, because we make
assumptions on data layout, but this is an artefact and I don't think it
is specified by the language wether the result is exact or not.

    Let's consider the following type:

typedef struct {int i; short h} sesqui_int;

    One would naively consider that sizeof(sesqui_int) is equal to 6.
But, with gcc, the value is 8, which looses 2 bytes in which it could
store a short or two chars. This is because this struct must be aligned
on a 4-byte boundary and, if you make an array of these,
sizeof(sesqui_int)*number_of_elements must give the size of the array.
Gcc has chosen to return a wrong sizeof() for the sake of preserving a
naive size arithmetic.

    Another implementation of the C language might decide to add
headers to arrays, in which it would store the size to perform strict
runtime checks. In this case the size of an array would be larger than
the sum of the sizes of its elements.

    Therefore this use of sizeof(), even though widespread, remains a
trick.

    Didier