C++ SIGSEGV Segmentation fault in loop - c++

I have the following code which ends up in a segmentation fault.
for (int a=0; a<inputFileList.size(); a++)
{
fileLines = readFile(inputFileList[a].c_str());
for (int i = 0; i < fileLines.size(); i++)
{
if (fileLines[i].find("text") != string::npos)
{
bool warnFound = false, errFound = false;
i++;
while (fileLines[i].find("message") == string::npos && i < fileLines.size())
{
if (fileLines[i].find("error") != string::npos)
errFound = true;
else if (fileLines[i].find("warning") != string::npos)
warnFound = true;
i++;
}
i--;
if (errFound)
errCtr++;
else if (warnFound)
warnCtr++;
else
okCtr++;
}
}
fileLines.clear();
}
When i remove the while-loop, i don't get this error anymore. But i don't know what's wrong with this loop.
Thx for your support

The while should probably read
while (i < fileLines.size() && fileLines[i].find("message") == string::npos)

This :
while (fileLines[i].find("message") == string::npos && i < fileLines.size())
should be:
while (i < fileLines.size() && fileLines[i].find("message") == string::npos )

I'm not sure if it has anything to do with the error you're getting, but you seem to have a problem with the i++ on line 7. It may increase i even when i == fileLines.size() - 1, so fileLines[i].find("message") on the next line would access a non-existing item.

Related

AlmostIncreasingSequence(CodeSignal)

I'm stuck in this challenge, and I thought of an algorithm which goes by:
bool almostIncreasingSequence(std::vector<int> Sequence)
{
int counter = 0;
Label:
std::vector<int>::iterator it = Sequence.begin();
for (it; it != Sequence.end(); it++)
{
if (*(it) >= *(it + 1))
{
counter++;
Sequence.erase(it);
goto Label;
}
}
return counter <= 1;
}
But I don't know why the output isn't right? What am I doing wrong in this code?
Here are the pictures of the challenge:
Make the return condition <= 2 and add an extra if statement to check if you would go out of bounds or not:
bool almostIncreasingSequence(std::vector<int> Sequence)
{
int counter{ 0 };
Label:
std::vector<int>::iterator it = Sequence.begin();
for (it; it != Sequence.end(); it++)
{
if ((it + 1 != Sequence.end())) //new if statement here
if (*(it) >= *(it + 1))
{
++counter;
Sequence.erase(it);
goto Label;
}
}
return counter <= 2;
}
hope it works!
Sorry I cant comment I need at least 50 rep, anyways... it has to do with the Label and goto statements, I have never seen such implementation, however removing the label and goto would work and make counter <= 1:
bool almostIncreasingSequence(std::vector<int> Sequence)
{
int counter{ 0 };
std::vector<int>::iterator it = Sequence.begin();
for (it; it != Sequence.end(); it++)
{
if ((it + 1 != Sequence.end()))
if (*(it) >= *(it + 1))
{
++counter;
}
}
return counter <= 1;
}
Here is an explanation: the goto statement is preventing the for statement from incrementing (++it), in other words using the goto would skip the increment part. This is what I think, again best of luck.
bool almostIncreasingSequence(vector<int> v) {
int n = v.size();
int cnt =0;
if(n == 1 )
return true;
for(int i=0; i<n-1; i++)
{
if(v[i]>=v[i+1])
{
if((v[i]-v[i+2] == 0))
cnt = 10;
cnt++;
}
}
if(cnt<=1)
return true;
else
return false;
}
was able to solve 17/19 test cases...let me know any further suggestions in this code.
Error for this test case [40, 50, 60, 10, 20, 30] .
problem statement link

Leetcode 28 - Implement strStr(): question

I am experiencing a bug in my submissions for Leetcode 28 that has thus far eluded me. My code works for most test cases but I am getting hung up on scenarios such as haystack = "mississippi", needle = "issip".
I have tried debugging and found that the entire haystack string is iterated through and it is returning -1 or not found. The substring length it is finding at each occurrence of 'i' is 4, 1, 1.
int strStr(string haystack, string needle) {
if (needle.empty()) {
return 0;
}
if (haystack.empty() && !needle.empty()) {
return -1;
}
int i = 0, j = 0, ans = 0;
for (i; i < haystack.length(); i++) {
if (haystack[i] == needle[0]) {
j = 0;
ans = i;
for (j; j < needle.length(); j++) {
/*
if (haystack[i++] == needle[j]) {
continue;
}
else {
break;
}
*/
if (haystack[i++] != needle[j]) {
break;
}
}
if (j == needle.length()) {
return ans;
}
}
if (j == needle.length()) {
return ans;
}
}
return -1;
}
Input: "mississippi", "issip"
Output: -1 (ans = 10, j = 1)
The function has several drawbacks.
For starters it should be declared like
std::string::size_type strStr( const std::string &haystack, const std::string &needle );
and if the second string is not found in the first string the function should return std::string::npos as all similar member functions of the class std::string do.
The function parameters shell be of constant referenced types.
The condition in this if-statement
if (haystack.empty() && !needle.empty())
has a redundant operand. It could be rewritten like
if (haystack.empty())
This loop
for (i; i < haystack.length(); i++)
should stop its iterations when the size of the tail of the first string is less than the size of the second string.
in this if-statement
if (haystack[i++] != needle[j]) {
the variable i is incremented that results in incrementing the variable two times: one in this statement and the second time in the loop.
The second pair of these statements
if (j == needle.length()) {
return ans;
is redundant.
The function can be written the following way as it is shown in the demonstrative program.
#include <iostream>
#include <string>
std::string::size_type strStr( const std::string &haystack, const std::string &needle )
{
if ( needle.empty() )
{
return 0;
}
else if ( haystack.empty() )
{
return -std::string::npos;
}
else
{
std::string::size_type ans = std::string::npos;
auto n1 = haystack.length();
auto n2 = needle.length();
for ( std::string::size_type i = 0; ans == std::string::npos && i + n2 <= n1; i++ )
{
std::string::size_type j = 0;
while ( j < n2 && haystack[i+j] == needle[j] ) j++;
if ( j == n2 ) ans = i;
}
return ans;
}
}
int main()
{
std::string haystack( "mississippi" );
std::string needle( "issip" );
std::cout << strStr( haystack, needle ) << '\n';
return 0;
}
Its output is
4
The problem is that you modify i in
if (haystack[i++] != needle[j]) {
Thus preventing a second potential match from being explored. Try
if (haystack[i + j] != needle[j]) {
and fix any knock-on issues. I expect it to work as-is, though.

C++ Matching Brackets 2 Solution not working

This problem which is similar to another that I solved here is giving me a wrong answer even though the algorithm works on the sample case.I have initialized all the variables this time and it works on a modified version of my previous algorithm.
#include <iostream>
int main() {
int n;
std::cin >> n;
int arr[n];
for (int i = 0; i <n ;++i) {
std::cin >> arr[i];
}
int four_count = 0, two_count = 0, three_long=0, one_long = 0 , max1_long = 0 ,max3_long = 0,a_depth = 0,max_depth = 0;
for (int i = 0; i < n; ++i) {
if (arr[i] == 3) {
if (arr[i+1] == 1) {
++a_depth;
if (a_depth > max_depth) {
max_depth = a_depth;
}
}
++four_count;
three_long += 2;
}
if (arr[i] == 1) {
if (arr[i+1] == 3) {
++a_depth;
if (a_depth > max_depth) {
max_depth = a_depth;
}
}
++two_count;
one_long += 2 ;
}
if (arr[i] == 2) {
if (arr[i+1] == 4 && i < n-1) {
--a_depth;
}
--two_count;
}
if (arr[i] == 4) {
if (arr[i+1] == 2 && i < n-1){
--a_depth;
}
--four_count;
}
if (four_count == 0 && two_count == 0) {
if (three_long >= one_long) {
if (three_long > max3_long) {
max3_long = three_long+one_long;
}
three_long = 0;
one_long = 0;
}
else {
if (one_long > max1_long) {
max1_long = one_long+three_long;
}
one_long = 0;
three_long = 0;
}
}
}
std::cout << max_depth*2 << " " << max1_long << " " << max3_long;
std::cout << "\n";
return 0;
}
Here is a link to the problem:
https://www.codechef.com/ZCOPRAC/problems/ZCO12003
In the below code:
for (int i = 0; i < n; ++i) {
if (arr[i] == 3) {
if (arr[i+1] == 1) {
when i reaches n-1, arr[i+1] becomes arr[n] resulting in an out-of-bounds memory access which will lead to undefined behaviour.
Let's say n is equal to 5. That means the array arr has the maximum index 4, because the first one is 0.
In your loop
for (int i = 0; i < n; ++i)
{ if (arr[i] == 3) {
if (arr[i+1] == 1) {
at some point i becomes n-1, so i == 4, then you try arr[i+1] meaning arr[5], which is out of bound.
Note that in the comment to P.Ws post, you tried if (arr[i+1] == 1 && i < n-1) to fix this. That won't work because there still is an arr[i+1] being executed. You could fix this by using
if(i < n-1) {
if(arr[i+1]) {
but that would mean an even deeper nesting of your ifs. You should probably rethink your approach to the given problem.
Edit: Are you sure you mean ++i and not i++?

How can I use openMP for loop parallel in this for loop?

Is it possible to use openMP for loop parallel here in this code? I tried and it shows 'break' has error. can anyone help me guide how to make this parallel with openMP?
The purpose of this code is to generate possible permutations of arithmetic expressions for a value. e.g. 5+5+1=11 and there may have many more expressions to get 11.
The problem is I want to use openMP to be paralle..but I don't know how can make it coz I am newbie in openMp and C++.
vector<string> solve(vector<int> question, vector<char> operands)
{
int targetAnswer = question.back(); //Get the final answer
question.pop_back(); //remove the final answer from question list
long int totalLoopingCount_Operands = pow(operands.size(),question.size()); // Calculate total looping numbers(operands)
bool isRedundantAnswer;
vector<string> answer;
sort(question.begin(), question.end());
do{
isRedundantAnswer = false;
vector<int> operationSequence;
//Fill up the operation sequence with first priority operands (int this case '*')
for (int i = 0; i < question.size(); i++) {
operationSequence.push_back(0);
}
//Start the answer seeking algorithm here
for (long int i = 0; i < totalLoopingCount_Operands-1; i++) {
if (operands[operationSequence[0]] == '*' || operands[operationSequence[0]] == '/') {
operationSequence[0]++;
continue;
}
string checkResult = checkAnswer(targetAnswer, operands, question, operationSequence); //Check the current equation
//check redundant answer
for (vector<string>::iterator it = answer.begin(); it != answer.end();it++) {
if (*it == checkResult) {
isRedundantAnswer = true;
}
}
//if result == -1, means this is not a solution
if (checkResult != "-1" && !isRedundantAnswer) {
answer.push_back(checkResult); //insert the answer into the list
}
//increment the operationSequence will change the equation
operationSequence[0]++;
for (int j = 0; j < question.size() - 1; j++) {
if (operationSequence[j] == operands.size()) {
operationSequence[j] = 0;
operationSequence[j + 1] ++;
}
}
if (operationSequence[i % (question.size() - 1)] == 5) {
cout << "error" << endl;
break;
}
}
} while (next_permutation(question.begin(),question.end()));
return answer;
}
In this solution the error is controlled by the foundError boolean which is modified ASAP the error is found and prevents threads picking other iterations to continue processing. The #pragma omp flush ensures that the modifications to the boolen variable is sent to main memory as soon as it is modified or before reading.
This is based from the solution discussed in http://www.thinkingparallel.com/2007/06/29/breaking-out-of-loops-in-openmp .
Notice also, that the solution needs a detailed study of which variables should be privatized or kept shared in the #pragma omp parallel for
bool foundError = false;
#pragma omp parallel for
for (long int i = 0; i < totalLoopingCount_Operands-1; i++) {
#pragma omp flush(foundError)
if (!foundError)
{
if (operands[operationSequence[0]] == '*' || operands[operationSequence[0]] == '/') {
operationSequence[0]++;
continue;
}
string checkResult = checkAnswer(targetAnswer, operands, question, operationSequence); //Check the current equation
//check redundant answer
for (vector<string>::iterator it = answer.begin(); it != answer.end();it++) {
if (*it == checkResult) {
isRedundantAnswer = true;
}
}
//if result == -1, means this is not a solution
if (checkResult != "-1" && !isRedundantAnswer) {
answer.push_back(checkResult); //insert the answer into the list
}
//increment the operationSequence will change the equation
operationSequence[0]++;
for (int j = 0; j < question.size() - 1; j++) {
if (operationSequence[j] == operands.size()) {
operationSequence[j] = 0;
operationSequence[j + 1] ++;
}
}
if (operationSequence[i % (question.size() - 1)] == 5) {
foundError = true;
#pragma omp flush(foundError)
}
}
}
if (foundError) {
cout << "error" << endl;
}

What are signals in netbeans C++ debugging

Hey guys I'm trying to debug my C++ application (running it produces no errors but also no output) and it gives me a signal caught error at this point.
'Signal received: ? (Unknown signal)'
Trying to continue with the debug gives me this message:
unrecognized or ambiguous flag word \"?\?
no registers
What could cause this?
The error occurs on this line:
if (input.at(i) == 'I') {
input is a string, given it's value by a user input (Roman Numeral)
Which is part of the following code (Converting Roman Numerals to Arabic Numbers):
//converting Roman Numerals to Arabic Numbers
int toArabic() {
//converts input to upper case
transform(input.begin(), input.end(), input.begin(), ::toupper);
int last_digit = 0;
int current_digit = 0;
int arabic = 0;
//checks that input matches desired numerals
for (int i = 0; i < sizeof(input); i++) {
if (input.at(i) == 'I' ||
input.at(i) == 'V' ||
input.at(i) == 'X' ||
input.at(i) == 'L' ||
input.at(i) == 'C' ||
input.at(i) == 'D' ||
input.at(i) == 'M') {
for (int i = 0; i < sizeof(input); i++) {
//Error occurs below
if (input.at(i) == 'I') {
current_digit = 1;
}
if (input.at(i) == 'V') {
current_digit = 5;
}
if (input.at(i) == 'X') {
current_digit = 10;
}
if (input.at(i) == 'L') {
current_digit = 50;
}
if (input.at(i) == 'C') {
current_digit = 100;
}
if (input.at(i) == 'D') {
current_digit = 500;
}
if (input.at(i) == 'M') {
current_digit = 1000;
}
if (last_digit < current_digit && last_digit != 0) {
current_digit -= last_digit;
arabic -= last_digit;
arabic += current_digit;
last_digit = current_digit;
current_digit = 0;
} else {
last_digit = current_digit;
arabic += current_digit;
current_digit = 0;
}
}
} else {
break;
}
}
return arabic;
}
I had this issue in C++ when I was actually reading invalid data which resulted in an Exception being thrown. Seems like NetBeans does not properly show that information when debugging. At least with version 8.1 and cygwin gdb I observed that problem.
Maybe a segmentation fault. Debug and check for NULL or invalid values.