Segfault in Cygwin but not VS, any ideas? - c++

It works with Visual Studio, but segfaults in Cygwin, which is weird because I'm compiling the same source, and both generate a Windows executable. GDB doesn't work very well for me in Cygwin for some reason, and the error doesn't appear in VS so I can't really debug it there.
Any ideas?
int main(void)
{
Pair ***occurences = new Pair**[20];
int i, j, k;
for (i = 0; i < 20; i++)
{
occurences[i] = new Pair*[i+1];
for (j = 0; j < i+1; j++)
{
occurences[i][j] = new Pair[26];
for (k = 0; k < 26; k++)
{
Pair pair;
pair.c = k + 'a';
pair.occurs = 0;
occurences[i][j][k] = pair;
}
}
}
std::fstream sin;
sin.open("dictionary.txt");
std::string word;
while (std::getline(sin, word))
{
if (word.size() < 21)
{
for (i = 0; i < word.size(); i++)
{
// SEGFAULTING HERE
occurences[word.size()-1][i][word[i] - 'a'].occurences++;
}
}
}
for (i = 0; i < 20; i++)
{
for (j = 0; j < i+1; j++)
{
delete [] occurences[i][j];
}
delete [] occurences[i];
}
delete [] occurences;
return 0;
}

You marked this line as the critical point:
occurences[word.size()-1][i][word[i] - 97].occurs++;
All three array accesses might go wrong here, and you would have to check them all:
It seems like the first dimension of the array has the length 20, so the valid values for the index are [0..19]. word.size()-1 will be less than 0 if the size of the word is zero itself, and it will be larger than 19 if the size of the word is 21 or more.
Are you sure the length of the word is always in the range [1..20]?
The second dimension has variable length, depending on the index of the first dimension. Are you sure this never gets out of bound?
The third dimension strikes me as the most obvious. You subtract 97 from the character code, and use the result as index into an array with 26 entries. This assumes that all characters are in the range of [97..122], meaning ['a'..'z']. Are you sure that there will never be other characters in the input? For example, if there are any capital characters, the resulting index will be negative.

Just reformulating my comment as an answer:
occurences[word.size()-1][i][word[i] - 'a'].occurs++;
if word.size() is 100 (for example) this will crash (for i == 0) since occurences has only 20 elements.

Related

C++ Convert one exact string element into an int

I want to create a string array and then after writing lines into it I want to change one exact character into int. I already know that all the characters are going to be numbers. As my goal is to change the one character at a time, options like atoi, stoi etc. are perhaps off? The closest I got is that:
#include <iostream>
int main()
{
int n=0,suma=0,i=0;
int multiplier[11]={1,3,7,9,1,3,7,9,1,3,1};
std::cin>>n;
std::string str[n];
for (int i = 0; i < n; ++i)
{
std::cin>>str[i];
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < 11; ++j)
{
i = str[i][j] - '0';
std::cout << i;
}
}
}
Although this is the output I get
"1-48"
I know that the string is going to be 11 characters long. Any ideas?
EDIT: It was a single typo that caused my confuse :p Yet still I'm looking forward to read and learn from your suggestions such as using different way to read n (from user input) strings. :)
In your loop:
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < 11; ++j)
{
i = str[i][j] - '0';
std::cout << i;
}
}
you are modifying outer loop variable i (looks like for the purpose of printing a value).
Given an unfortunate input, you would go out-of-bounds fast.

How to Compare multiple variables at the same time in the C++?

I'm making Sudoku validater program that checks whether solved sudoku is correct or not, In that program i need to compare multiple variables together to check whether they are equal or not...
I have provided a snippet of code, what i have tried, whether every su[][] has different value or not. I'm not getting expecting result...
I want to make sure that all the values in su[][] are unequal.
How can i achieve the same, what are mistakes in my snippet?
Thanks...
for(int i=0 ; i<9 ;++i){ //for checking a entire row
if(!(su[i][0]!=su[i][1]!=su[i][2]!=su[i][3]!=su[i][4]!=su[i][5]!=su[i][6]!=su[i][7]!=su[i][8])){
system("cls");
cout<<"SUDOKU'S SOLUTION IS INCORRECT!!";
exit(0);
}
}
To check for each column uniqueness like that you would have to compare each element to the other ones in a column.
e.g.:
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
for (int k = j + 1; k < 9; ++k) {
if (su[i][j] == su[i][k]) {
system("cls");
cout << "SUDOKU'S SOLUTION IS INCORRECT!!\n";
exit(0);
}
}
}
}
Since there are only 8 elements per row this cubic solution shouldn't give you much overhead.
If you had a higher number N of elements you could initialize an array of size N with 0 and transverse the column. For the i-th element in the column you add 1 to that elements position in the array. Then transverse the array. If there's a position whose value is different from 1, it means you have a duplicated value in the column.
e.g.:
for (int i = 0; i < N; ++i) {
int arr[N] = {0};
for (int j = 0; j < N; ++j)
++arr[su[i][j] - 1];
for (int i = 0; i < N; ++i) {
if (arr[i] != 1) {
system("cls");
cout << "SUDOKU'S SOLUTION IS INCORRECT!!\n";
exit(0);
}
}
}
This approach is way more faster than the first one for high values of N.
The codes above check the uniqueness for each column, you would still have to check for each row.
PS: I have not tested the codes, it may have a bug, but hope you get the idea.

Non-Space delimited text file to 2D vector

I've got a file that can be of any size and is a series of char values without any spaces between (except a blank space is treated as a blank cell of a grid).
xxxxxxx
xx xx
xxyyyxx
After some great help I've gone with the method to use a vector<vector<char> > however I cannot seem to populate it.
void readCourse(istream& fin) {
// using 3 and 7 to match example shown above
vector<vector<char> > data(3, vector<char>(7));
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 7; j++) {
fin.get(data[i][j]); // I believe the problem exists here
} // Does the .get() method work here?
} // Or does it need to be .push_back()?
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 7; j++) {
cout << data[i][j];
}
}
}
Is my method for populating my 2D vector valid? If not, can you please point me in the right direction?
I'd keep it simple and efficient with a single vector<char>:
vector<char> readCourse(istream& fin) {
vector<char> course(3*(7+2)); // 3x7 plus newlines
fin.read(course.data(), course.size());
course.resize(fin.gcount());
auto end = remove(course.begin(), course.end(), '\n');
end = remove(course.begin(), end, '\r');
course.erase(end, course.end()); // purge all \n and \r
return course;
}
That's a single input operation to get all the data, followed by removing the characters you don't need. You can then access the result in a 2D way like this:
course.at(x + y*7) // assuming width 7
That may seem a bit inconvenient, but it is efficient and compact--the overhead is always three pointers and a single heap allocation, instead of being proportional to the number of rows.
Solution I ended up using after ADT implementation:
void readCourse(std::istream& fin) {
std::vector<std::string> level
std::string line;
while(std::getline(fin, line) {
level.push_back(line);
}
for (std::size_t i = 0; i < 3; i++) {
for (std::size_t j = 0; j < 7; j++) {
std::cout << data[i][j];
}
std::cout << std::endl;
}
}

For loop overflow vector size

I have two vectors - one is global and second one local. I need to copy elements from local vector to global in order 1st, 4th, 7th, ... In the local one is array of size 6. My code works fine but it always make one more iteration which leads to loading wrong data. On the last iteration it also copy wrong data. Do you have any idea what is wrong in my code?
int iter = 0;
float nr;
for (i = 0; i < vect_local.size(); i++){
iter += 1;
nr = vect_local[i];
vect_global.push_back(nr);
i += 2;
if((vect_local.size()/iter) == 3){
iter = 0;
break;
}
}
EDIT: for (i = 0; i < = vect_local.size(); i++)
Stupid typo. But my problem is still the same...
your loop condition should be i < vect_local.size() because the last index is size-1
int iter = 0;
float nr;
for (i = 0; i < vect_local.size(); i+=3){
// ^
Maybe Something like this ?
int main () {
int globalarray[16]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int localarray[6]={0,0,0,0,0,0};
int internalcounter=0;
for(int i=0;i<int(sizeof(globalarray)/sizeof(int));i=i+3)
{
localarray[internalcounter] = globalarray[i];
internalcounter+=1;
}
for(int i=0;i<6;i++)
{
cout<<localarray[i]<<endl;
}
return 0;
}
That prints :
1
4
7
10
13
16

Getting run time error working with vectors

So, I read the problem 4.5 from Accelerated C++, and interpreted it rather wrong. I wrote a program which is supposed to display counts of a word in string. However, I have probably done something very stupid, and very wrong. I can't figure it out.
Here's the code: http://ideone.com/87zA7E.
Stackoverflow says links to ideone.com must be accompanied by code. Instead of pasting the all of it, I will just paste the function which I think is most likely at fault:
vector<str_info> words(const vector<string>& s) {
vector<str_info> rex;
str_info record;
typedef vector<string>::size_type str_sz;
str_sz i = 0;
while (i != s.size()) {
record.str = s[i];
record.count = 0;
++i; //edit
for (str_sz j = 0; j != s.size(); ++j) {
if (compare(record, s[j]))
++record.count;
}
for (vector<str_info>::size_type k = 0; k != s.size(); ++k) {
if (!compare(record, rex[k].str))
rex.push_back(record);
}
}
return rex;
}
One problem is that you have this:
str_sz i = 0;
while (i != s.size()) {
but you never increment i, leading to an endless loop. Inside of that loop, you're pushing elements into vector rex. A vector cannot contain an infinite number of elements.
Also, you are trying to access:
rex[k].str
in
for (vector<str_info>::size_type k = 0; k != s.size(); ++k) {
if (!compare(record, rex[k].str)) // rex is empty in the beginning!!
rex.push_back(record);
}
But you do not know whether rex has k+1 elements in it.
EDIT: Change your code to:
while (i != s.size()) {
// read new string into a record (initial count should be one).
str_info record;
record.str = s[i];
record.count = 1;
// check if this string already exists in rex
bool found = false;
for (vector<str_info>::size_type k = 0; k < rex.size(); ++k) {
if ( record.str == rex[k].str ) {
rex[k].count++;
found = true;
break;
}
}
i++;
if ( found )
continue;
// if it is not found then push_back to rex
rex.push_back( record );
}