Reputation: 23
Going through C++ Primer Plus. I'm working on the exercises for chapter 5. Let me preface this with the second exercise I am working:
Redo Listing 5.4 using a type array object instead of a built-in array and type long double instead of long long.Find the value of 100! (factorial)
And the listing in question:
// formore -- more looping with for
#include <iostream>
int main()
{
const int aSize = 100;
long long factorials[aSize];
factorials[1] = factorials[0] = 1LL;
for (int i = 2; i < aSize; ++i)
factorials[i] = i * factorials[i-1];
for (int i = 0; i < aSize; ++i)
std::cout << i << "! = " << factorials[i] << std::endl;
return 0;
}
I've rewritten the code, following the exercises instructions and came out with the following:
// redo listing 5.4 using long double and arrays instead - find value of 100!
#include <iostream>
#include <array>
int main()
{
int const ArSize = 100;
std::array<long double, ArSize> factorials = {1.0L, 1.0L};
for (int i = 2; i <= ArSize; ++i)
factorials[i] = i * factorials[i-1];
for (int i = 0; i <= ArSize; ++i)
std::cout << i << "! = " << factorials[i] << std::endl;
return 0;
}
When I try and run this code, I get undefined behaviour. I'm quite sure it has something to do with the long double type I'm using as when I switch factorials to type double, the program runs fine. What exactly is causing this?
My apologies if I'm asking an obvious question, it tried to google the exercise but most people seem to skip it and just do Exercise three instead...
EDIT
Changed ArSize to:
const int ArSize = 101;
For loops:
for (int i = 2; i < ArSize; ++i)
factorials[i] = i * factorials[i-1];
for (int i = 0; i < ArSize; ++i)
std::cout << i << "! = " << factorials[i] << std::endl;
I am still getting UB; factorials[0] to factorials[3] display as neg. 0
See here:
I get the feeling something here is going right over my head.
Upvotes: 2
Views: 344
Reputation: 227628
You are assigning out of bounds here,:
for (int i = 2; i <= ArSize; ++i)
factorials[i] = i * factorials[i-1];
and here:
for (int i = 0; i <= ArSize; ++i)
std::cout << i << "! = " << factorials[i] << std::endl;
and that is UB. Solution: don't access an array out of bounds.
Note: it is not do do with the double or the std::array
. You changed the loop conditions, introducing a bug.
Upvotes: 7