mpi determinant, CODE: 11 segmentation fault - c++

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.

Related

Why is in the following similar codes one giving runtime error and other is not

Well this is really weird
Consider the following two codes :-
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
for(int i = 0; i < 5; i++)
{
*ptr[i]=a[i];
}
for(int i = 0; i < 5; i++)
{
cout<<*(ptr[i]);
}
}
AND
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
*ptr[0]=a[0];
*ptr[1]=a[1];
*ptr[2]=a[2];
*ptr[3]=a[3];
*ptr[4]=a[4];
cout<<*(ptr[0])<<endl;
cout<<*(ptr[1])<<endl;
cout<<*(ptr[2])<<endl;
cout<<*(ptr[3])<<endl;
cout<<*(ptr[4])<<endl;
}
The first one gives runtime errorr , while the seconde one gives 1 ,2 ,3 ,4 ,5 output , I can't find the difference between the two codes , can anyone help me to find the difference .
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
*ptr[0]=a[0];
*ptr[1]=a[1];
cout<<*(ptr[0])<<endl;
cout<<*(ptr[1])<<endl;
}
the above code runs fine and gives output 1, 2
but
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
*ptr[0]=a[0];
*ptr[1]=a[1];
*ptr[2]=a[2];
cout<<*(ptr[0])<<endl;
cout<<*(ptr[1])<<endl;
cout<<*(ptr[2])<<endl;
}
this code gives runtime error on codeblocks(gcc) , I am just getting more confused
I have both runtime errors.
The result of recoding with the pointer variable below.
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
for(int i = 0; i < 5; i++)
{
ptr[i]=&a[i];
}
for(int i = 0; i < 5; i++)
{
cout<<*(ptr[i]);
}
}
It is already established that
*ptr[0] = a[0];
with unallocated pointer is undefined behavior.
The solution
ptr[0] = &a[0];
is also already given. This works, but it is limited because now, the ptr array is tied to a, which you not always want. In that case you might want
ptr[0] = new int(a[0]);
This initializes the array with values from a but keeps it independent. However, this introduces manual memory management and this can become tricky in more complex code (memory leaks, double deallocations, dangling pointers), so a more C++ like solution would be (assuming the pointers point to something more interesting than an integer, because now there seems to be no need for pointers).
#include <memory>
#include <vector>
#include <iostream>
int main() {
int a[]={1,2,3,4,5};
std::vector<std::unique_ptr<int>> ptrs;
for(auto i: a)
{
ptrs.emplace_back(std::make_unique<int>(i));
}
for(auto& i: ptrs)
{
std::cout << *i;
}
}

c++ program crashes before main

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.

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.

Dining philosophers and mutex initialization

I am trying to solve dining philosophers problem.So I pretty much made entire code but the problem is that I can't initialize monitors(i've made pseudocode which I re-written in c++) so really I can't test the program. Can anyone help me and say what's the issue with initialization of monitor/mutex_init ?
I get error on line 18 and it goes like:
error: ‘int pthread_mutex_init’ redeclared as different kind of symbol
changing it into int pthread_mutex_init(&monitor,NULL); WON'T work !
by adding
int pthread_mutex_init(pthread_mutex_t *monitor, NULL);
I get error: expected identifier before ‘__null’
#include <iostream>
#include <cstdio>
#include <pthread.h>
#include <cstdlib>
#include <unistd.h>
using namespace std;
char v_filozofi[5]={'O'}; //vizualni prikaz filozofa
int stapic[5]={1}; //stapici za filozofe
int broj[5]; //shema koju sam mora sloziti da imam broj filozofa
pthread_t d_filozofi[5]; //dretve filozofa,philosopher's thread
pthread_cond_t red_uvjeta[5];
pthread_mutex_t monitor; //deklariramo monitor,tj mymutex
int pthread_mutex_init(*monitor,NULL);
void ispisi_stanje(int n){
for(int i = 0; i < 5 ;i++) cout<< v_filozofi[i];
cout<<"("<< n+1 << ")" <<endl;
}
void misliti(int n){
cout<<"Mislim " << endl;
sleep(4);
}
void jesti(int n){
pthread_mutex_lock(&monitor);
v_filozofi[n]='o';
while(stapic[n]==0 || stapic[n+1]%5==0){//gleda ima li lijevi i desni
//stapic na raspolaganju
pthread_cond_wait(&red_uvjeta[n],&monitor);
}
stapic[n] = stapic[(n+1)%5] = 0;
v_filozofi[n] = 'X';
ispisi_stanje(n);
pthread_mutex_unlock(&monitor);
sleep(2);
pthread_mutex_lock(&monitor);
v_filozofi[n] = 'O';
stapic[n] = stapic[(n+1)%5] = 1;
pthread_cond_signal(&red_uvjeta[(n-1)%5]);
pthread_cond_signal(&red_uvjeta[(n+1)%5]);
ispisi_stanje(n);
pthread_mutex_unlock(&monitor);
}
void * filozof(void *n){
int br_fil = *((int *)n);
while(1){
misliti(br_fil);
jesti(br_fil);
}
return 0;
}
//MAIN
int main(){
for(int i=0;i<5;i++){
broj[i] = i;
pthread_cond_init(&red_uvjeta[i],NULL);
}
for(int i=0;i<5;i++){
sleep(1);
pthread_create( &d_filozofi[i],NULL,filozof,&broj[i]);
}
for(int i=0;i<5;i++) pthread_join(d_filozofi[i],NULL);
pthread_mutex_destroy(&monitor);
return 0;
}
remove the line
int pthread_mutex_init(*monitor,NULL);
and instead do
pthread_mutex_init(&monitor,NULL);
at the beginning of your main function. (and check that it returns 0)
As it is you are declaring the function not calling it, and since it's already declared you get an error
This function expects a pointer, and why did you put "int" before the call? I think you confused a prototype (which is unecessary) and an actual call to the function.
int pthread_mutex_init(*monitor,NULL);
So:
pthread_mutex_init(&monitor,NULL);
http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_mutex_init.html
once take a look at this one nicely given
http://nitish712.blogspot.in/search/label/mutex
http://nitish712.blogspot.in/2012/09/classical-ipc-problems.html

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?