-2

Receive data stream from network and I want to print out the received data. The following is part of my program.

struct BestPriceField
{
    double  BidPrice1;
    int     BidVolume1;
    double  AskPrice1;
    int     AskVolume1;
};

// convert network order to host order (double)
double ntoh64(uint8_t *input)
{
    double rval;
    uint8_t *data = (uint8_t *)&rval;

    data[0] = input[7];
    data[1] = input[6];
    data[2] = input[5];
    data[3] = input[4];
    data[4] = input[3];
    data[5] = input[2];
    data[6] = input[1];
    data[7] = input[0];
    return rval;
}

// get data from network data stream
struct *best_price = receive_from_network();
printf("BidPrice1:%.0lf, BidVolume1:%u, AskPrice1:%.0lf, AskVolume1:%u\n",
    ntoh64((uint8_t *)&best_price->BidPrice1) , 
    ntohl(best_price->BidVolume1), 
    ntoh64((uint8_t *)&best_price->AskPrice1) , 
    ntohl(best_price->AskVolume1));
printf("BidPrice1:%.0lf, BidVolume1:%u, AskPrice1:%2X,   AskVolume1:%u\n",
    ntoh64((uint8_t *)&best_price->BidPrice1) ,
    ntohl(best_price->BidVolume1), 
    ntoh64((uint8_t *)&best_price->AskPrice1) , 
    ntohl(best_price->AskVolume1));

After running this code, I got the following result.

BidPrice1:145210, BidVolume1:3, AskPrice1:0, AskVolume1:4193532217
BidPrice1:145210, BidVolume1:3, AskPrice1:F9F43939, AskVolume1:66

I just changed the output format of AskPrice1 from "%.01f" to "%2X", but the result of AskVolume1 was also changed.

Why could this happen?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Luis
  • 77
  • 1
  • 10
  • 1
    Enable all compiler warnings. Certainly they will provide rapid feedback about coding mishaps in `printf()`. – chux - Reinstate Monica Sep 18 '17 at 02:27
  • If there was just some information about the `printf` functions (and all other standard functions). And maybe something to search the web for such information. Hmm, I really should google if there are such things ... – too honest for this site Sep 18 '17 at 12:58

1 Answers1

0

Using the wrong format specifier causes undefined behaviour. Undefined behaviour means that anything can happen. Including, but not limited to, unexpected output.

There is no reason to expect some particular output for the second line (or the first line for that matter, since undefined behaviour can time-travel).

M.M
  • 138,810
  • 21
  • 208
  • 365