I was trying to solve a simple question on a coding site. I must find how many pairs are there in an array that sumed up are divisible by a given integer k. The logic in the code below is bad, I've got 100p afterwards, but I found a strange bug in the bad code.
Here it is:
#include <bits/stdc .h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);
int divisibleSumPairs(int n, int k, vector<int> ar) {
int modK[k] = {0};
for(int i = 0; i < n; i)
modK[ar[i] % k];
int cnt = 0;
///cout << modK[0] << '\n'; <- If I uncomment this, the output is 1
cnt = modK[0] * ((modK[0]) - 1) / 2;
if(k % 2 == 0)
cnt = (modK[k / 2] * (modK[k / 2] - 1)) / 2;
else
for(int i = 0; i < k / 2; i)
cnt = modK[i] * modK[k - i];
return cnt;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string first_multiple_input_temp;
getline(cin, first_multiple_input_temp);
vector<string> first_multiple_input = split(rtrim(first_multiple_input_temp));
int n = stoi(first_multiple_input[0]);
int k = stoi(first_multiple_input[1]);
string ar_temp_temp;
getline(cin, ar_temp_temp);
vector<string> ar_temp = split(rtrim(ar_temp_temp));
vector<int> ar(n);
for (int i = 0; i < n; i ) {
int ar_item = stoi(ar_temp[i]);
ar[i] = ar_item;
}
int result = divisibleSumPairs(n, k, ar);
fout << result << "\n";
fout.close();
return 0;
}
string ltrim(const string &str) {
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);
return s;
}
string rtrim(const string &str) {
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);
return s;
}
vector<string> split(const string &str) {
vector<string> tokens;
string::size_type start = 0;
string::size_type end = 0;
while ((end = str.find(" ", start)) != string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end 1;
}
tokens.push_back(str.substr(start));
return tokens;
}
If I comment out cout << modK[0] << '\n';
, the ouput (in an out file, not on the screen) is 65141, If I don't it is 1. Why?
This is the problem:
CodePudding user response:
The modK[k - i]
accesses out of bounds when i
is 0. This should probably be modK[k - i - 1]
.
CodePudding user response:
In C , the size of an array must be a compile time constant. So you cannot write code like:
int n = 10;
int arr[n]; //incorrect
Correct way to write this would be:
const int n = 10;
int arr[n]; //correct
For the same reason the following statement is incorrect in your code :
int modK[k] = {0}; //incorrect because k is a function parameter
Also take a look at: Why should I not #include <bits/stdc .h>
You can/should also use the debugger to check the value of the indices and see if you are trying to access out of bound element of the array. This is a common reason for undefined behavior.