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.
Related
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 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?
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <stdlib.h>
using namespace std;
int gradeExam(string answerKeyARR[]);
int main()
{
const int QUESTIONS = 10;
const int MAX_STUDENTS = 250;
ifstream inFile;
ofstream outFile;
inFile.open("grade_data.txt");
outFile.open("grade_report.txt");
string ansKey;
inFile >> ansKey;
string answerKeyARR[QUESTIONS];
//Loop for storing each answer into an array rather than all in a single string.
for (int j = 0; j < QUESTIONS; j++)
{
answerKeyARR[j] = ansKey.substr(j,1);
}
int i = 0;
int numStudents = 0;
string studentAnswers[MAX_STUDENTS];
//Loop to read in all answers into array and count number of students.
while (!inFile.eof())
{
inFile >> studentAnswers[i];
numStudents++;
i++;
}
//WHY DOES IT CRASH HERE?!
string studentAnswersARR[numStudents][QUESTIONS];
for (int k = 0; k < numStudents; k++)
{
for (int l = 0; l < QUESTIONS; l++)
{
studentAnswersARR[k][l] = studentAnswers[l].substr(l,1);
cout << studentAnswersARR[k][l];
}
}
inFile.close();
outFile.close();
return 0;
}
Okay, so basically once it gets to the part where it's removing the substring, it crashes. It works perfectly fine for retrieveing the answerkey answers, so why the hell is it crashing when it gets to this point? This is still a WIP for basic coding 2.
Also, when I change variable 'l' to, say, position 0, it works. What gives?
There are multiple issues with your code that may cause problems.
First, your input loop is not bounded properly. It should stop at MAX_STUDENTS, but you fail to check for this limit.
Second, do not use eof() to check for the end of file. There are many posts on SO discussing this.
while (!inFile && i < MAX_STUDENTS)
{
inFile >> studentAnswers[i];
numStudents++;
i++;
}
The next issue is the line you highlighted in your question. It probably crashes due to stack space being exhausted. But the code you have uses a non-standard C++ extension, and once you do that, then the rule as to what that line really does internally is up to the compiler vendor.
So to alleviate this with using standard C++, the following can be done:
#include <vector>
#include <string>
#include <array>
//...
std::vector<std::array<std::string, QUESTIONS> >
studentAnswersARR(numStudents);
I am trying to learn arrays and I can not figure out this code. For some reason when I run this an error is identified, but the entire code is highlighted as the error so I am confused as to where the error really is. I know this is very basic, but any help would be very appreciated.
#include <iostream>
using namespace std;
int main()
{
int x[8];
for (int i =0; i<= 8; i++)
x[i] = i;
return 0;
}
Try
#include <iostream>
using namespace std;
int main()
{
int x[8];
for (int i =0; i<8; i++)
x[i] = i;
return 0;
}
Because arrays start at 0 accessing array index 8 is to far as that is actually slot 9.
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.