r/cprogramming • u/Remarkable-Tap9486 • Feb 10 '26
Getting integer overflow issues way before it should be.
As a c beginner, today I've decided to play with integer overflow problem and wrote a tiny c program for Fibonacci sequence. Starting from element of index 47 I get problems, but as I am using uint64_t type array then I guess theoretically I could go up to 93.
#include <stdio.h>
#include <inttypes.h>
int main() {
uint64_t fib[1000] = {0, 1};
// calculate elements of sequence
for (int i = 2; i < 1000; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
// print the result
for (int i = 0; i < 100; i++) {
printf("fib[%d] = %d \n", i, fib[i]);
}
return 0;
}
10
Upvotes
29
u/Plastic_Fig9225 Feb 10 '26 edited Feb 10 '26
printf("%d", x) interprets x as signed int, which is not the same as uint64_t. Try e.g. printf("%" PRIu64, x) to make sure you get the correct format specifier. C.f. https://en.cppreference.com/w/c/header/inttypes.html
9
u/[deleted] Feb 10 '26
Others have told you the issue. You should also tell the compiler to give you more warnings.
-Wall -Wextra -pedantic for starters.
2
u/epasveer Feb 10 '26
Without giving you the direct answer, I'll give you a hint. Check how you're printing the "fib" values.
2
u/ffd9k Feb 10 '26
%dis just for printing int. If for example uint64_t isunsigned long(that is platform-dependent), you can print it with%lu. To get the right printf format specifier no matter what platform you are on, you can use thePRIu64constant (which is string literal like "lu" defined in stdint.h), like this:printf("fib[%d] = %"PRIu64" \n", i, fib[i]);1
u/Ok_Leg_109 Feb 10 '26
This will help explain why you need to print it differently.
Two's complement - Wikipedia