c++ program crashes before main - c++

When I run my code below, the program crashes and the compiler message is Segmentation fault. I've searched for bugs in my code but I can't find any. My program doesn't even seem to enter main(), because I've tried using 'cout' to see where it crashes but I get no output, even when 'cout'-ing immedeately after main starts. Here is the code. Can someone tell me what the problem is?
#include <cmath>
#include <stdio.h>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct edge_t
{
int a,b,w;
};
bool comp(edge_t a, edge_t b)
{
if(a.w < b.w)
return true;
return false;
}
vector<int> parent;
int find_parent(int x)
{
if(parent[x] == x)
return x;
parent[x] = find_parent(parent[x]);
return parent[x];
}
void join(int a,int b)
{
parent[find_parent(a)] = find_parent(b);
return;
}
int mst(vector<edge_t> v)
{
sort(v.begin() , v.end() , comp);
for(int i=0;i<v.size();++i)
parent[i] = i;
int sum = 0;
for(int i=0;i<v.size();++i)
{
if(find_parent(v[i].a) != find_parent(v[i].b))
{
join(v[i].a, v[i].b);
sum += v[i].w;
}
}
return sum;
}
int main() {
cout<<"Hello?\n"; ///does not display anything QQ
int n,m;
scanf("%d %d",&n,&m);
parent.resize(n);
int p,q,r;
vector<edge_t> edges;
int s =0;
for(int i=0;i<m;++i)
{
scanf("%d %d %d",&p,&q,&r);
edge_t tmp;
tmp.a = p;
tmp.b = q;
tmp.w = r;
s+=r;
edges.push_back(tmp);
}
printf("%d\n", s - mst(edges));
return 0;
}
I'm using the online ide on hackerrank.com (I'm practising problems there).

Inside your mst function
for (int i = 0; i<v.size(); ++i)
parent[i] = i;
This assumes that parent has the same or more elements that v, and if that's not the case, your program crashes.
In the same function, you are calling find_parent and you haven't verified that a & b are lower than parent.size(), which would be fine if you checked that in your find_parent function, but you don't check it there either.
if (find_parent(v[i].a) != find_parent(v[i].b))
{
join(v[i].a, v[i].b);
sum += v[i].w;
}
Therefore, if find_parent gets invalid input, your program crashes
int find_parent(int x)
{
if (parent[x] == x)
return x;
}

Depending on your compilation environment if you have an instruction set enabled that your system does not support (e.g. AVX) crashes can occur prior to main (I have seen this happen on Windows with VC++). Try compiling with all optimisations switched off, for an "ancient" target architecture.
Depending on your platform, this could also be due to shared libraries not being found, although this seems less likely.
EDIT: Deleted the bit about cout since you have a end line character and main. That was an off thought.

Related

global vairable did not initialize correctly between running multiple test cases in c++

I am still actively learning c++ with a strong background in python3, the point of this question is not seeking any help with solving the problem Decode Variations on leetcode or pramp, but to understand the compilation or syntax related issue in c++.
The following code using dfs runs well if I run it case by case, however on pramp, it failed in RUN TESTS! Very surprising! It seems like in test case #2 int n=0; was not initialized and used the output of n in test case #1 as its value rather than 0, see the console in the attached screenshot at the end.
#include <iostream>
#include <string>
using namespace std;
int n=0;
void dfs(const string& s, int i){
if (i==s.size()){
n++;
return;
}
if ( 0<s[i]-'0' && s[i]-'0'<10)
dfs(s, i+1);
if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
dfs(s, i+2);
}
int decodeVariations(const string& s)
{
dfs(s,0);
cout<<n<<endl;
return n;
}
int main()
{
return 0;
}
Here is the code to run test case #2:
int main()
{
const string s = "26";
dfs(s,0);
cout<<n<<endl;
return 0;
}
If I added another initialization of n=0; to int decodeVariations(const string& s), then everything works fine. I try to become a programmer with a clear mind, please educate me.
Yes, non-const global variable is evil. Even though I don't know how leetcode and pramp (especially, the main function is empty) run a number of test cases, but I get a hunch it runs test case in the main function, which only compile and run the code once. Thus the global did not get reinitialized.
#include <iostream>
#include <string>
using namespace std;
int n=0;
void dfs(const string& s, int i){
if (i==s.size()){
n++;
return;
}
if ( 0<s[i]-'0' && s[i]-'0'<10)
dfs(s, i+1);
if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
dfs(s, i+2);
}
int decodeVariations(const string& s)
{
dfs(s,0);
return n;
}
int main(int argc, char **argv){
for (int i=1;i<argc;i++)
cout<<decodeVariations(argv[i])<<endl;
}
run with ./test 26 26 26
output:
2
4
6
Quick fix is to get rid of global variable
#include <iostream>
#include <string>
using namespace std;
//int n=0;
int dfs(const string& s, int i){
int ans = 0;
if (i==s.size()){
return 1;
}
if ( 0<s[i]-'0' && s[i]-'0'<10)
ans += dfs(s, i+1);
if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
ans += dfs(s, i+2);
return ans;
}
int decodeVariations(const string& s)
{
// your code goes here
int n;
n = dfs(s,0);
cout<<n<<endl;
return n;
}

getting Floating point exception (core dumped). I dont know how to fix it

In the key function is gives the error. Atleast thats what gdb says. Thanks in Advance.
#include <stdio.h>
#include <stdlib.h>
#include <iostream> // for cin and cout in C++
#include <cassert> // for assert
#include <strings.h>
#include <string.h>
#include<time.h>
using namespace std;
int lcombinations=0;
int distinct=0;
linear hash function.
void linear(char *tword, int key, int n, char **lcArray)
{
int c;
while(c==0)
{
if(key==n)
{
key=0;
}
if(strlen(lcArray[key])==0)
{
lcArray[key]=tword;
c=1;
}
else
{
key++;
lcombinations++;
}
}
}
generates key for the hash function
void key(char *tword, int l, int n, char **lcArray)
{
int total=0;
int k;
for(int i=0; i<l; i++)
{
total= total+tword[i];
}
total=n%total;
k=rand()%25+66;
total=total*k;
linear(tword, total, n, lcArray);
}
int counter=0;
finds all the distinct words in the test.
void distinct_words(char *tword, char **distinct, int l, int n, char **lcArray)
{
int j;
int k=0;
if(counter==0)
{
counter++;
distinct[0]=tword;
key(tword,l,n,lcArray);
}
else
{
for(j=0; j<counter; j++)
{
if(strcmp(distinct[j],tword)!=0)
{
k++;
}
}
if(k==counter)
{
distinct[counter]=tword;
counter++;
key(tword,l, n, lcArray);
}
}
}
receives and breaks the text into words
int main()
{
srand(time(NULL));
FILE *inFile;
char word[81];
char *tword;
inFile = fopen("will.txt", "r"); // Open for reading, hence the "r"
assert( inFile); // make sure file open was OK
int i=0;
int n=65437;
int j,k;
char **distinct= (char **)malloc(sizeof(char **)*n);
char **lcArray= (char **) malloc(sizeof(char*)*n);
for(int p=0; p<n; p++)
{
lcArray[p]= (char *) malloc(sizeof(char)*81);
}
while(fscanf(inFile, "%s",word) != EOF)
{
i++;
k= strlen(word);
tword= (char *)malloc(sizeof(char)*k);
int l=0;
for(j=0; j<k; j++)
{
if(isalnum(word[j]))
{
word[j]=toupper(word[j]);
tword[l]=word[j];
l++;
}
}
printf("%s ", tword);
distinct_words(tword, distinct, l, n, lcArray);
}
}
My suspicion is that your floating point exception is generated by this line:
total=n%total;
... specifically, if total is zero, that can cause a floating point exception on many systems.
You can avoid the exception by guarding against the possibility of the modulo value being zero:
if (total != 0)
{
total=n%total;
}
else
{
printf("Hey, modulo by zero is undefined! (It's similar to divide-by-zero!)\n");
total = 0; // or something
}
By the way, one key thing you'll need to learn -- if you want to retain your sanity while programming -- is how to track down exactly where in your code a crash is occurring. You can do this using a debugger (by single-stepping through the code's execution, and/or by setting breakpoints), or you can deduce where the crash occurred by sprinkling temporary printf()'s (or similar) throughout your code so that you can see what gets printed just before the crash, and use that to narrow down the problem location. Either technique will work, and one or the other is usually necessary when merely eyeballing the code doesn't give you the answer.

Error: No Matching function to call to 'online'

I know this is probably a really simple fix, but I'm having trouble finding what my error is, and none of the posts I've checked online have been able to help me. I get the error on the cout lines. Here's the code:
#include <iostream>
bool online(int a, int network[a][a]) {
/*post condition: returns true if every switch in a network is of even degree. Otherwise, returns false.*/
int switches;
for(int x=0; x < a; x++) {
switches = 0;
for(int y=0; y < a; y++)
if(network[x][y])
switches += 1;
if(switches & 1)
return 0;
}
return 1;
}
int main() {
int arrayOne[6][6] =
{
{0,1,1,0,0,0},
{1,0,0,1,0,0},
{1,0,0,1,0,0},
{0,1,1,0,1,1},
{0,0,0,1,0,1},
{0,0,0,1,1,0}
};
int arrayTwo[8][8] =
{
{0,1,1,0,0,0,0,0},
{1,0,0,1,0,0,0,0},
{1,0,0,1,0,0,0,0},
{0,1,1,0,1,0,0,0},
{0,0,0,1,0,1,1,0},
{0,0,0,0,1,0,0,1},
{0,0,0,0,1,0,0,1},
{0,0,0,0,0,1,1,0}
};
std::cout << online(6, arrayOne) << std::endl;
std::cout << online(8, arrayTwo) << std::endl;
}
For C99 (which supports variable length arrays), there is no <iostream>. Make sure you are compiling the program as C and not C++, and then use <stdio.h> instead, and include <stdbool.h>.
printf("%d\n", online(6, arrayOne));
printf("%d\n", online(8, arrayTwo));
For C++, variable length arrays may not be supported for your compiler. You should use a template instead for online().
template <unsigned a>
bool online(int, int (&network)[a][a]) {
//...
}

mpi determinant, CODE: 11 segmentation fault

I'm new to mpi and I want to write a program in C++ that calculates the determinant of a matrix and in the beginning of trying to write it I get this error when trying to compile with mpi compiler.
#include "mpi.h"
#include <iostream>
#include <stdio.h>
#include "/usr/include/malloc.h"
using namespace std;
int matrix[3][3] = {{1,2,3},
{4,5,6},
{7,8,9}};
//**************
int** MakeMatrix (int** oldMatrix,int I,int J,int m,int n)
{
int** newMatrix = (int**)malloc(sizeof(int*)*J);
for(int i=0;i<J;i++)
{
newMatrix[i] = (int*)malloc(sizeof(int)*I);
}
for(int i=0;i<I-1;i++)
for(int j=0;j<J-1;j++)
if(i>=m)
if(j>=n)
{
newMatrix[i][j]=oldMatrix[i+1][j+1];
}
else
{
newMatrix[i][j]=oldMatrix[i+1][j];
}
else
{
newMatrix[i][j]=oldMatrix[i][j];
}
return newMatrix;
}
///////////////////////
int determinan (int** lmatrix,int I,int J)
{
if(I*J==1)
{
return lmatrix[I-1][J-1];
}
int minus = -1;
int sum = 0;
for(int j=0;j<J-1;j++)
{
for(int k=1;k<I+j+1;k++,minus*=minus);
sum += minus*lmatrix[0][j]*determinan(MakeMatrix(lmatrix,I,J,0,j),I-1,J-1);
}
return sum;
}
///*************
int main(int argc,char **argv)
{
//MPI_Init(&argc,&argv);
cout<<determinan((int**)matrix,3,3)<<'\n';
//MPI_Finalize();
return 0;
}
and here is the error message :
===================================================================================
= BAD TERMINATION OF ONE OF YOUR APPLICATION PROCESSES
= EXIT CODE: 11
= CLEANING UP REMAINING PROCESSES
= YOU CAN IGNORE THE BELOW CLEANUP MESSAGES
===================================================================================
YOUR APPLICATION TERMINATED WITH THE EXIT STRING: Segmentation fault (signal 11)
This typically refers to a problem with your application.
Please see the FAQ page for debugging suggestions
I am sure there are multiple problems. The immediate one is the type cast in:
cout<<determinan((int**)matrix,3,3)<<'\n';
^^^^^^^
This isn't a valid cast since matrix isn't an array of pointers.

Code Crashes Immediately After Running

Even at the bare minimum of 10 numbers to input, I get no errors but my code crashes immediately on running. I was also wondering, what should I do if I have a question similar to another question that I've already asked, but on another new problem?
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int primer(int max);
int main()
{
primer(5);
system("pause");
return 0;
}
int primer(int max){
vector<int> a;
a[1]=2;
for (int i=2;i<=max;i++){
bool prime=true;
for (int ii=0;ii<a.size();ii++) {
if (i/a[ii]==floor(i/a[ii])) {
prime=false;
}
}
if (prime==true) {
a.push_back(i);
}
}
for (int iii=0;iii<=a.size();iii++) {
cout << a[iii] << endl;
}
}
I get no errors but the compiled code crashes immediately.
I changed it to
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int primer(int max);
int main()
{
primer(5);
system("pause");
return 0;
}
int primer(int max){
vector<int> a;
a.push_back(2);
for (double i=2;i<=max;i++){
bool prime=true;
for (int ii=0;ii<a.size();ii++) {
if (i/a[ii]==floor(i/a[ii])) {
prime=false;
}
}
if (prime) {
a.push_back(i);
}
}
for (int iii=0;iii<=a.size();iii++) {
cout << a[iii] << endl;
return a.size();
}
}
I addressed all of your problems. It still returns no errors and still crashes.
What makes you think you can do this?
vector<int> a;
a[1]=2;
vector<int> a;
a[1]=2;
You can't access a[1] until you've reserved space for it. You should probably use a.push_back(2) to append 2 to the end of a.
You have declared primer to return int, yet it returns nothing. Either make it void or return the number of primes.
i/a[ii]==floor(i/a[ii]) isn't going to do what you expect. i/a[ii] performs integer division. You should cast i to double before dividing.
if (prime==true) can be changed to simply if (prime), no need to compare a boolean to true.
Please improve your coding style. Use proper indentation and more commonly used variable names: i, j, k instead of i, ii, iii.
Here is another bug:
for (int iii=0;iii<=a.size();iii++) {
cout << a[iii] << endl;
return a.size();
}
My understanding is that you can only return once from a function, main included. The execution will not loop here because of the return statement.
Did you really want a return statement inside a for loop?