c++ – Silent Integer Overflow: std::stoi

Notice the example code produces a silent integer overflow even when using these AI suggested compiler options:

What are the recommended gcc/msvc compiler options to catch this insidious bug?

godbolt.org/z/zqfqhYTnP

#include 
#include 

char buf[4096] = "4096";
int bufsize = 4;

size_t buggy = std::stoi(std::string(buf, bufsize)) * 1024 * 1024;

size_t fixed = std::stoull(std::string(buf, bufsize)) * 1024ULL * 1024ULL;

int main() {
    printf("buggy = %zu\n", buggy);
    printf("fixed = %zu\n", fixed);
}

x86-64 gcc (trunk) -Wall -Wextra

buggy = 0
fixed = 4294967296

x64 msvc v19.latest /W4

buggy = 0
fixed = 4294967296

Read more here: Source link