Search code examples
c++cmath

c++ program doesn't execute with `#include<cmath>`


I'm writing a program for my class that solves a few problems one after another. This part:

#include <iostream>
#include <fstream>
#include <cmath>

using namespace std;

int main() {

    ifstream data;
    data.open("data.txt");

    //LOAD VALUES
    int d[200][320];

    for(int i=0;i<200;i++){
        for(int j=0;j<320;j++){
            data>>d[i][j];
        }
    }

int m=1,c=0;//max length, current length

    for(int i=0;i<320;i++){//columns
        for(int j=1;j<200;j++){//rows

            if(d[i][j]==d[i][j-1])c+=1;
            else if(c>m){
                m=c;    
                c=0;
            }
            else c=0;

        }
    }

    cout<<"max length: "<<m<<endl;
return 0;
}

searches for the longest vertical line of identical values in an array. I commented other parts of the program, one of which requires the cmathlibrary. When I compile the above part with#include<cmath> the execution lasts unreasonably long and gives no output on cout, just a blank line. It works properly when I don't include cmath. Any idea why this is so and how to fix it? Here's the link to "data.txt"

Edit: It stopped working even after deleting #inclde<cmath>. Whether the program executes correctly seems to be completely random.


Solution

  • Including cmath has nothing to do with your issue.

    You have undefined behavior called buffer overflow when analyzing data. Here is live demo with index checking (exception is thrown). Basically you have messed up order of indexes.

    Here is fixed version of your code (with index checking).

    BTW your code is very messy, learn to split code into smaller functions. Primitive demo (can be done better, but for beginner should be fine).