A funny thing with sprintf

后端 未结 6 2023
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 14:17

I\'m so confused with sprintf that a funny problem with different platfrom. Code :

int main () 
{
    char sql[1024];
    uint32_t app_id = 32;
    uint64_t          


        
6条回答
  •  一生所求
    2020-12-15 14:38

    The format specifier is wrong. The printf function doesn't know what kind of parameters are passed to it, it can only deduce this from the format specifiers. So when you pass a 64bit integer to it, and tell the function that you passed only a long (32bit) then it takes only half of the 64 bit value passed in. Depending on the architecture, the correct result might be printed or not. The reason is how the number is stored in memory and what the printf function sees when it reads the long value.

    If the long value happens to have the same number of bits or the value is stored in memory in such a way that the expected result happens to be in the right place, the correct value could be printed, but of course, the code would still be wrong, though it appears to work.

提交回复
热议问题