I am working on a USACO task and the grader outputs 4, while my machine gives 3, the correct answer.
The input is:
4
7 Mildred +3
4 Elsie -1
9 Mildred -1
1 Bessie +2
I have run this through a debugger and no issues were found.
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <fstream>
using namespace std;
int N, bmilk=7, emilk=7, mmilk=7;
int bboard=0, eboard=0, mboard=0;
int ans=0;
vector<pair<int,pair<string,int>>> a;
int main()
{
ofstream fout("measurement.out");
ifstream fin("measurement.in");
fin >> N;
for (int i = 0; i < N; i++)
{
int d, chg;
string c;
fin >> d >> c >> chg;
a.push_back(make_pair(d,make_pair(c,chg)));
}
sort(a.begin(), a.end());
for (int i = 0; i < N; i++)
{
if (a[i].second.first=="Bessie") bmilk+=a[i].second.second;
else if (a[i].second.first=="Elsie") emilk+=a[i].second.second;
else mmilk+=a[i].second.second;
int best_milk = max(bmilk,max(emilk,mmilk));
int curr_board[4];
for (int j = 0; j < 3; j++) curr_board[i]=0;
if (bmilk==best_milk) curr_board[0]=1;
if (emilk==best_milk) curr_board[1]=1;
if (mmilk==best_milk) curr_board[2]=1;
if (curr_board[0]!=bboard||curr_board[1]!=eboard||curr_board[2]!=mboard)
{
ans++;
bboard=curr_board[0];
eboard=curr_board[1];
mboard=curr_board[2];
}
}
fout << ans << "\n";
return 0;
}
Can anybody please help me find what is causing this error?
You read uninitialized elements of curr_board, and you potentially overrun it as well.
The problem is that the line intended to initialize multiple elements, instead assigns the same element over and over:
for (int j = 0; j < 3; j++) curr_board[i]=0;
Reading uninitialized values is undefined behavior and could easily cause different outcomes on different machines. Ditto for out-of-bounds access.
Why does curr_board have size 4 anyway?
Related
I have received this bound error though the sample input and output match. I tried several ways to solve this error, but I couldn't. Please help me to overcome this problem. And also please, explain why? what is the main reason for this error?. My code as follows:
#include <iostream>
using namespace std;
int main(){
int a[4];
for(int i=1; i<=4; i++){
cin >> a[i];
}
string s;
cin >> s;
int sum = 0;
for(int i =0; i<s.size(); i++){
if(s[i]=='1'){
sum=sum+a[1];
}
else if(s[i]=='2'){
sum+=a[2];
}
else if(s[i]=='3'){
sum+=a[3];
}
else if(s[i]=='4'){
sum+=a[4];
}
}
cout << sum << endl;
}
Sample input:
1 2 3 4
123214
Output:
13
Array indexes start at 0 so a[4] is out of bounds in your case.\
Since we're here I recommend to not use C arrays. Use std::array or std::vector instead.
Also it's better to use the range for.
First of all, this is not correct
int a[4];
for(int i=1; i<=4; i++){
cin >> a[i];
}
arrays in C++ are indexed from 0, so it should be if you want to have a[1] = 1
int a[5];
for(int i = 0; i < 5; i++){
cin >> a[i];
}
Side note. You dont need the "look-up array". To sum numbers, you can just do:
sum += (s[i] - '0');
int a[4];
for(int i=1; i<=4; i++){
The variable declaration for a allocates indices 0 to 3 (4 elements total), yet you're trying to access 0 to 4 via i
I'm having trouble with a C6385 warning in my code. I'm trying to see if two arrays will equal each other. The warning I keep getting is on the line where if(p[i] == inputGuess[j]). I have tried redoing these line but I keep getting the same warning. Does anyone know what I'm doing wrong. This is also my first time programming in C++.
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include "Game.h"
#include <iostream>
#include <iomanip>
using namespace std;
int* generateNumbers(int n, int m) {
// Intialize random number
srand(static_cast<unsigned int>(time(NULL)));
// Declare array size to generate random numbers based on what is between 1 to (m)
int* numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = (rand() % m) +1;
cout << numbers[i]<< " " << endl;
}
return numbers;
}
void Game::guessingGame(int n, int m) {
int* p;
int sum = 0;
// Call the generateNumber function
generateNumbers(n, m);
// Declare array based on user guesses
inputGuess = new int[n];
p = generateNumbers(n,m);
for (int i = 0; i < n; i++) {
cin >> inputGuess[i];
}
// See if the user guesses and computers answers match up
for (int i = 0; i < n; i++) {
for (int j = 0; i < n; j++) {
if (p[i] == inputGuess[j]){ //Where I keep getting the C6385 Warning
sum++;
break;
}
}
}
}
The C6385 warning documentation states:
The readable extent of the buffer might be smaller than the index used
to read from it. Attempts to read data outside the valid range leads
to buffer overrun.
https://learn.microsoft.com/en-us/cpp/code-quality/c6385?view=msvc-160
Your second if statement compares i < n instead of j < n and since i is never modified inside it will run forever. This causes the warning since you’ll access memory out of bounds. Fix the comparison.
I created this program:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int n;
cin>>n;
vector<int> m(n);
for(int i=0;i<n;i++){
cin>>m[i];
}
sort(m.begin(),m.end());
vector<bool> used(n,false);
for(int i=n;i>0;i--){
for(int j=i;j>0;j--){
if((m[i]/m[j]>=2)&&(used[i]==false))
used[j]=true;
}
}
int numOfElem=0;
for(int i=0;i<n;i++){
if(used[i]!=true){
numOfElem++;
}
}
cout<<"\n"<<numOfElem<<"\n";
return 0;
}
Now for some reason right after I input elements of vector m I get command terminated, does anyone know the cause of this problem?
You access the vectors m and used out of bounds since you start iterating with i == n (the size of the vectors). This causes your program to have undefined behavior and a crash is one possible outcome of that.
Suggested fix:
for(int i = n - 1; i >= 0; i--) { // start with n-1 and ...
for(int j = i; j >= 0; j--) { // ... include 0 in the loop
Also note that m[i] / m[j] may be a division by zero and throw an exception, so you may want to check if m[j] == 0 before doing the division too.
I am a beginner to C++.
I am trying to read in input from the console, so I have the code below:
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
#define maxn 2006
int A[maxn][maxn];
int main() {
memset(A,0,sizeof(A));
int n = 0,m = 0;
cin >> n >> m;
for(int i = 0; i < n; ++i){
string str; cin >> str;
for(int j =0; j < m; ++j)
A[i][j] = str[j]-'0';
}
return 0;
}
A sample input looks like this
5 7
0101010
1000101
0101010
1010101
0101010
My program above works perfectly.
However, for learning purpose, I did nothing but move the declaration of 2D int array A into the main function, which looks like this:
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
#define maxn 2006
int main() {
int A[maxn][maxn];
memset(A,0,sizeof(A));
int n = 0,m = 0;
cin >> n >> m;
for(int i = 0; i < n; ++i){
string str; cin >> str;
for(int j =0; j < m; ++j)
A[i][j] = str[j]-'0';
}
return 0;
}
I rebuild it and run, I get segmentation fault 11.
Anyone know what's going on here? Why does the code break down after the subtle change?
Thanks!
Anyone know what's going on here?
Yes: stack overflow.
By moving the variable you made it a local (stack allocated) instead of global (allocated at startup in the BSS section of the binary).
The size of your variable is 16,096,144 bytes (2006 * 2006 * 4). And stack is usually limited, often to 8MB. On a UNIX system, after ulimit -s unlimited, your modified program may start working again.
I am trying to write a sudoku solver.
I got the input almost done, but something strange started happening. On the index [i][9] of int sudoku[i][9], there are numbers present that I have never put there.
For example, when I run the code below with the input that is commented below using namespace std;, the output is:
410270805
085146097
070580040
927451386
538697412
164328759
852704900
090802574
740965028
Of course, I only need 0 through 8, but I was wondering what is causing integers to appear at the 9th index.
This is the code:
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
/*
410270805
085146097
070580040
927451386
538697412
164328759
852704900
090802574
740965028
*/
int main()
{
int sudoku[9][9];
int solving[9][9][9];
int input;
for (int i=0; i<=8; i++) {
cin >> input;
int j;
int k;
for (j=8, k=1; j>=0; j--, k++) {
int asdf = input/pow(10,k-1);
sudoku[i][j] = asdf % 10;
}
}
cout << endl;
for (int i=0; i<=8; i++) {
for (int j=0; j<=9; j++) {
cout << sudoku[i][j];
}
cout << endl;
}
return 0;
}
Accessing elements outside of the defined region of an array is Undefined Behavior (UB).
That means it could:
Allow you to access uninitialized space (what yours is doing hence the random numbers)
Segfault
Any number of other random things.
Basically don't do it.
In fact stop yourself from being able to do it. Replace those arrays with std::vectors and use the .at() call.
for example:
std::vector<std::vector<int>> sudoku(9, std::vector<int>(9, 0));
for (int i=0; i<=8; i++) {
for (int j=0; j<=9; j++) {
cout << sudoku.at(i).at(j);
}
cout << endl;
}
Then you will get a thrown runtime exception that explains your problem instead of random integers or segfaults.
I think I found your problem, at your very last for loop you used j <= 9 instead of j <= 8. You then tried to write (j) leaving the possibility of it writing 9 wide open. Try replacing that 9 with 8.