sizeof - C++ fread: unsigned char and short mixture -


i have sample code here:

    unsigned char *m_fbytes;     m_fbytes = (unsigned char*)malloc(m_ibytelen1framedecoded*sizeof(short));      int err;     err = fread(m_fbytes, sizeof(short), 960, fin);     curr_read = err;     for(int i=0;i<curr_read;i++)     {         opus_int32 s;         s=m_fbytes[2*i+1]<<8|m_fbytes[2*i];         s=((s&0xffff)^0x8000)-0x8000;         m_in[i]=s;     }      int ilen = encode(m_enc, m_in, m_ibytelen1framedecoded, m_data, m_max_payload_bytes); 

i don't understand line:

err = fread(m_fbytes, sizeof(short), 960, fin); 

the authors of code read bytes (aka unsigned char), pass sizeof(short).

why use "sizeof(short)"?

the code contains couple of tacit assumptions make unnecessarily fragile. way read bytes used

s=m_fbytes[2*i+1]<<8|m_fbytes[2*i]; s=((s&0xffff)^0x8000)-0x8000; 

the assumptions are

  • char_bit == 8; that's pretty safe assumption nowadays, unless 1 deals exotic hardware, it's not guaranteed.

  • sizeof(short) == 2; that's true, not guaranteed either.

the way read bytes used, each adjacent pair of them make 1 unit in final result (and using 2 instead of sizeof(short) more robust, if sizeof(short) > 2, use part of read data [if sizeof(short) == 1, char_bit must @ least 16, in case stuff break in different way]).

the size parameter fread used specify how many bytes make 1 unit, no partial units read, , buffer contains err complete units.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -