Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf redifines UINT32_MAX

Tags:

c

printf

code:

#include <stdio.h>
#include <stdint.h>

int main(int argc, char *argv[]) {
    printf("%lu\n%lu\n%lu\n%lu\n%lu\n%lu\n%lu\n",
        UINT32_MAX,
        UINT32_MAX,
        UINT32_MAX,
        UINT32_MAX,
        UINT32_MAX,
        UINT32_MAX,
        UINT32_MAX);
    return 0;
}

output:

4294967295
4294967295
4294967295
4294967295
4294967295
18446744073709551615
18446744073709551615

bug or intentional? and why? i think it speaks for itself but the interface needs me to add more lines before i can post it (to much code for to less text lol)

like image 844
Matombo Avatar asked Dec 01 '22 16:12

Matombo


2 Answers

You are using %lu, this is incorrect. The %lu specifier is for unsigned long and only unsigned long, not uint32_t. This is why the output is incorrect. Use PRIu32 instead.

Your compiler should have caught this error for you, if you were compiling with warnings enabled.

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h> // defines PRIu32

printf(
    "%" PRIu32 "\n"
    "%" PRIu32 "\n"
    "%" PRIu32 "\n"
    "%" PRIu32 "\n"
    "%" PRIu32 "\n"
    "%" PRIu32 "\n"
    "%" PRIu32 "\n",
    UINT32_MAX,
    UINT32_MAX,
    UINT32_MAX,
    UINT32_MAX,
    UINT32_MAX,
    UINT32_MAX,
    UINT32_MAX);

In practice, PRIu32 is defined to "u" on most systems.

like image 148
Dietrich Epp Avatar answered Dec 05 '22 05:12

Dietrich Epp


This is undefined behavior: you are passing unsigned int, but your %lu format tells printf that you are passing long unsigned int. This leads to undefined behavior, because printf goes by what the format specifier says (in fact, it has no other way to find out, because type information is not passed to printf).

Once you fix your format issue, the problem goes away:

printf("%u\n%u\n%u\n%u\n%u\n%u\n%u\n",
    UINT32_MAX,
    UINT32_MAX,
    UINT32_MAX,
    UINT32_MAX,
    UINT32_MAX,
    UINT32_MAX,
    UINT32_MAX);

This prints

4294967295
4294967295
4294967295
4294967295
4294967295
4294967295
4294967295

Demo.

like image 29
Sergey Kalinichenko Avatar answered Dec 05 '22 06:12

Sergey Kalinichenko