Tuesday, November 16, 2010

Sscanf

The problem with the following code:

   short myShort; sscanf("5", "%d", &myShort);

is "%d" should be "%hd".

For this example, assume a short is 16 bits and an int is 32-bits. Since &myShort is a pointer to 16-bits, and the format code "%d" specifies a 32-bit number, when sscanf writes to myShort, it will write 32 bits to a 16-bit object. This wipes out the next 16-bits of data. This can cause nasty intermittent/latent bugs.

No comments:

Post a Comment