4

In chapter 5.10.1 of Programming: Principles and Practice using C++, there is a "Try this" exercise for debugging for bad input of an area. The pre-conditions are if the the inputs for length and width are 0 or negative while the post-condition is checking if the area is 0 or negative. To quote the problem, "Find a pair of values so that the pre-condition of this version of area holds, but the post-condition doesn’t.". The code so far is:

#include <iostream>
#include "std_lib_facilities.h"

int area (int length, int width) {
    if (length <= 0 || width <= 0) { error("area() pre-condition"); }
    int a =  length * width;
    if(a <= 0) { error("area() post-condition"); }
    return a;
}

int main() {

int a;
int b;
while (std::cin >> a >> b) {
    std::cout << area(a, b) << '\n';
}

system("pause");
return 0;
}

While the code appears to work, I can't wrap my head around what inputs will get the pre-condition to succeed yet will trigger the post-condition. So far I have tried entering strings into one of the inputs but that just terminates the program and tried looking up the ascii equivalent to 0, but same result as well. Is this supposed to be some sort of trick question or am I missing something?

Tom Blodget
  • 20,260
  • 3
  • 39
  • 72
mcbalsa
  • 51
  • 5
  • 8
    Consider using large values for the input so that the multiplication overflows. – Hans Passant Apr 11 '18 at 14:48
  • Oh, it triggered, thanks Hans – mcbalsa Apr 11 '18 at 14:52
  • @HansPassant that would be undefined behavior since it's signed integer overflow ... so no guarantee that it'll do anything – UKMonkey Apr 11 '18 at 15:01
  • That's obvious. I don't know Stroustrup's didactic, but he doesn't strike me as the kind of guy that won't give beginners a chance to see what UB looks like. If you don't know how to trigger it then you're guaranteed to cause it. – Hans Passant Apr 11 '18 at 15:09
  • 1
    It's also a toy example -- postconditions check that the function itself isn't buggy. – Quentin Apr 11 '18 at 15:41
  • @mcbalsa You can write an answer and when you're satisfied that it's the best, correct answer, you can accept it. – Tom Blodget Apr 11 '18 at 23:27

3 Answers3

1

Consider using large values for the input so that the multiplication overflows.

mcbalsa
  • 51
  • 5
0

Numbers which when multiplied cause signed overflow will possibly cause the value to be negative and certainly cause the result to be incorrect.

Exactly what values cause integer overflow will depend on your architecture and compiler, but the gist is that multiplying two 4 byte integers will result in an 8 byte value, which can not be stored in a 4 byte integer.

QuestionC
  • 10,006
  • 4
  • 26
  • 44
0

I tried this, and seems like this works: area(1000000,1000000);

The output was: -727379968

Abhishek Keshri
  • 3,074
  • 14
  • 31