Runtime error in C++ with eigen library, any suggestions? - c++

I am new to C++ and eigen library. I am trying to code some simple stuff, but do not know where I am going wrong. Here is my code:
#include<iostream>
#include<Eigen\Dense>
#include<cmath>
#include<fstream>
using namespace std;
using namespace Eigen;
int main (int argc, char* argv[])
{
int n = 200;
Matrix<double, Dynamic,1> u_n;
u_n.setZero(n,1);
Matrix<double, Dynamic,1> u_n_minus_one;
u_n_minus_one.setZero(n,1);
Matrix<double, Dynamic,1> u_n_plus_one;
u_n_plus_one.setZero(n,1);
std::ofstream fileWriter ("Values.txt");
assert(fileWriter.is_open());
float r=2;
float F=100;
for (int t=0;t<=5;t=t+1)
{
u_n_plus_one (0,0) =0;
//source of error
u_n_plus_one.block(1,0,n-1,0) = pow(r,2)*( u_n.block(1,0,n-2,0)+ u_n.block(3,0,n,0)) + 2*(1-pow(r,2))*u_n.block(1,0,n-1,0)-u_n_minus_one.block(1,0,n-1,0);
//source of error
u_n_plus_one (floor(n/2),0)=F;
u_n_plus_one (n-1,0) =0 ; //corrected from (n,0) to (n-1,0)
u_n_minus_one = u_n ;
u_n = u_n_plus_one ;
//writing values to file
if (remainder(t, 10) == 0)
{
fileWriter<<u_n.transpose()<<std::endl;
}
}
fileWriter.close();
}
I am trying to declare a few matrices (though they are vectors). Then I am doing operations on blocks of matrices, and finally writing the results to the file. I did not get any compile time error, but program crashes during run.
I tried debugging the code and the error seem to lie within //source of error statements. Can someone help me with this?

As the page on Block operations says, matrix.block(i,j,p,q) denotes the block with p rows and q columns starting at the (i,j) entry. I think that u_n.block(3,0,n,0) in the program is supposed to refer to the block starting at the (3,0) entry and ending at the (n,0) entry, but in fact it refers to the block starting at the (3,0) entry and of size (n,0). The block starting at the (3,0) entry and ending at the (n,0) entry is denoted by u_n.block(3,0,n-2,1) or u_n.segment(3,n-2) or u_n.tail(n-2); see the link mentioned at the start.

Related

What is the origin of the double free errors in my use of the G+Smo library?

I am using the G+Smo library for some interpolation, and keep running in "double free or corruption" errors at runtime when using the library functions. Eventually, my goal is to wrap it in order to call this from much user-friendlier Python.
The minimal working example I have written is the following:
#include "gismo.h"
#include <vector>
using namespace std;
int main()
{
vector<real_t> pos_nodes;
real_t periode_x = 1.0;
index_t nb_nodes_x = 10;
for (int i = 0; i<nb_nodes_x; i++)
{
pos_nodes.push_back(periode_x/(nb_nodes_x+1) * i);
}
gismo::gsKnotVector<real_t> nodex(pos_nodes, 3);
// Create a node vector based on the positions given
cout << nodex;
gismo::gsTensorBSplineBasis<2, real_t> base(node_x, node_x);
// Create a Tensor BSpline Basis based on the node vectors
cout << base;
gismo::gsMatrix<real_t>; // Until there everything works
// base.anchors_into(res); // Uncomment any of those lines and runtime will crash
// res = base.anchors(); // Uncomment any of those lines and runtime will crash
return 0;
}
This code compiles, even with one of the last 2 lines uncommented, but gives errors at runtime.
The function anchors_into is defined in gsTensorBasis.h as:
template<short_t d, class T>
void gsTensorBasis<d,T>::anchors_into(gsMatrix<T>& result) const
{
gsMatrix<T> gr[d];
gsVector<unsigned, d> v, size;
result.resize( d, this->size() );
for (short_t i = 0; i < d; ++i)
{
gr[i] = m_bases[i]->anchors();
size[i] = this->size(i);
}
// iterate over all tensor product basis functions
v.setZero();
unsigned r = 0;
do {
// Make tensor product of greville points
for (unsigned i=0; i<d; ++i )
result(i,r)= (gr[i])( 0, v(i) );
++r ;
} while (nextLexicographic(v, size));
}
I have tried defining the res variable globally (it solved the problem at another place in my code, not here), or using the function anchor_into(10, res) to find the anchor of the 10th base function, but when I execute, all options end up with:
...blabla printing the node vector...
...blabla printing the basis definition...
double free or corruption (out)
Aborted (core dumped)
I have no idea where to look for problems, if I misuse the library or if the library itself has a problem. I've gone through quite a few questions about similar errors on this website, but most were linked to personal class/struct definitions, which I do not do.

Reading Matrix Market file C++ issues

I'm trying to read and use a matrix market file, but my current attempts haven't produced anything. I'm extremely new to C++ so be gentle. Here's what I've got so far:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <algorithm>
using namespace std;
int main()
{
ifstream f("GX30.mtx");
int m,n,l;
while(f.peek()=='%') f.ignore(2048, '\n');
f>>m>>n>>l;
cout<<l;
int I[m],J[n],val[l];
int mat[m][n];
for(int i=1;i<=l;i++)
{
f>>I[i]>>J[i]>>val[i];
}
for(int k=1; k<=l;k++)
{
mat[I[k]][J[k]]=val[k];
cout<<"test";
}}
My test output produces nothing, and none of the variables determining the matrix parameters initialize properly. The first few lines from the file I'm reading from are as follows:
%%MatrixMarket matrix coordinate integer general
%% X {5,5} [[30,8,3]] [ (b*a^-1)^3 ]
12 30 60
1 1 1
1 3 1
1 4 1
The first line not proceeded by % indicates the number of rows, then columns, then lastly the number of non zero entries (I think)
Then the following lines index the row and column position of each entry, with its corresponding value.
There are few issues you need to fix.
The main problem is how you access arrays. Array index starts from 0, not 1. Array sizes are different in your application too.
I[m],J[n],val[l];
m, n, l are not equal so you go beyond boundaries of two arrays:
for(int i=1;i<=l;i++)
for(int k=1; k<=l;k++)
You code most likely causes an access violation and crashes, hence you don't even see the result of cout<<l; operation.
You shouldn't access all array from a single loop like you do. Something like the following is alright.
for (int i = 0; i < l; ++i)
{
val[i] ... // val array, not I or J here
}
Also, Matrix Market allows for float values but you are using integers.
Yet another thing: Lines may be separated by "\r", "\n" and "\r\n" but you expect '\n'. Does Matrix Market format specify anything or it relies on OS conventions? If lines are separated with '\r' then your code may not work:
while(f.peek()=='%') f.ignore(2048, '\n');

Inconsistency between int and bool

I just implemented breadth first search in c++ and instead of declaring a vector as bool, I declared it as an int. This lead to a very odd observation. When I used int, the code printed the following:
1
32763
-524268732
Throughout the entire code, I don't provide any such value to variable as the 2nd and 3rd node receive, so I assume that they are just garbage values, but why do garbage values even come up, when I'm initialising the vector to be full of zeroes ??? You may check the code to be that below:
#include <iostream>
#include <queue>
using namespace std;
queue<int> neigh;
vector< vector<int> > graph(3);
vector<int> flag(3, 0);
int main(void)
{
graph[0].push_back(1); graph[0].push_back(2);
graph[1].push_back(0); graph[1].push_back(2);
graph[2].push_back(0); graph[3].push_back(1);
neigh.push(0);
while(!neigh.empty())
{
int cur = neigh.front();
neigh.pop();
flag[cur] = 1;
for(int i = 0, l = graph[cur].size();i < l;i++)
{
if(!flag[graph[cur][i]])
neigh.push(graph[cur][i]);
}
}
for(int i = 0;i < 3;i++)
{
cout << flag[i] << endl;
}
}
Alright, then I changed just a single line of code, line number 7, the one where I declare and initialise the flag vector.
Before:
vector<int> flag(3, 0);
After:
vector<bool> flag(3, false);
And voila! The code started working:
1 //The new output
1
1
So, my question is, what is the problem with the code in the first place ? I believe it may be some kind of error I made, or possibly that its only by chance that my bfs implementation works at all... So, what is the truth, SO? What is my (possible) mistake ?
You are accessing your vector out of bounds here:
graph[3].push_back(1);
At this moment, graph only has three elements. This leads to undefined behaviour.

Segmentation Fault reason unknown Opencv

I have the following code compiled in linux terminal (c++ in linux) and am using OpenCv 2.4.3.
However, am getting a segmentation fault in run time and I really have no clue as to why. I have placed differnt cout statements to know if the program processed to the particular stage but in vain. Could you please help me? Please explain me what exactly is this segmentation fault. Am stuck here for a long time.
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include <stdlib.h>
using namespace cv;
using namespace std;
int main()
{
cout<<"check"<<flush;
Mat src,src_gray,dst;
int kernel_size = 3;
int scale = 1;
int delta = 0;
int ddepth = CV_16S;
char* window_name = "sharpness estimate";
int freq,rows,cols =0;
double *estimate,*min = 0;
Point *minLoc,*maxLoc = 0;
src = imread("/home/siddarth/examplescv/erez images/image53.jpg");
if( !src.data )
{
return -1;
}
namedWindow(window_name,CV_WINDOW_AUTOSIZE);
Mat abs_dst;
cvtColor(src,src_gray,CV_RGB2GRAY);
Laplacian(src_gray,dst,ddepth,kernel_size,scale,delta,BORDER_DEFAULT);
convertScaleAbs(dst, abs_dst);
minMaxLoc(dst,min,estimate,minLoc,maxLoc,noArray());
Size s = dst.size();
rows = s.height;
cols = s.width;
cout<<rows<<endl<<cols<<endl;
for(int i=0;i<=rows;i++)
{
for(int j=0;j<=cols;j++)
{
if(dst.at<double>(i,j) >= *estimate-100
&& dst.at<double>(i,j) <= *estimate+100)
{
cout<<freq++;
}
}
}
cout<<"estimate :"<<*estimate<<endl;
cout<<"frequency :"<<freq<<endl;
imshow(window_name,abs_dst);
waitKey(1000);
return 0;
}
The code doesn't cross the first "check" print statement just after the main function declaration. That is the confusing issue. But once I flushed the first print statement, it got executed. I am still facing issues.
Make sure you insert std::endl into cout so that the buffer is flushed. This will probably be why you're not seeing any output.
One immediate issue is that your for loops check the condition with <=, meaning that you're probably going one past the end. But since you're using at, you should have an exception thrown (assuming this Mat type acts like a standard container).
Also, you're creating lots of pointers to pass as some function arguments (for example, double* estimate). This doesn't actually give you a double object though, just a pointer. Unless the function you're passing them to is allocating a double for you (which I hope it's not), you're doing it wrong. You should be doing:
double estimate;
minMaxLoc(/* ... */, &estimate, /* ... */);
You'll need to do that with all of the values you're getting through output parameters.
Another thing to note: Doing int i, j = 0; only initialises j to 0, but not i. You need to do int i = 0, j = 0;.
Okay, I'm going to explain why fixing the initialisers works. I had to look up the definition of minMaxLoc to see what happens. Basically, the function is something like the following:
void setToFive(int* x)
{
if (x) {
*x = 5;
}
}
This function will take a pointer to an int, and then set that int to the value 5. However, if the pointer passed is a null pointer, the value will not be set (otherwise there'll be undefined behaviour because you're derefencing a null pointer). Basically, passing a null pointer says "I don't care about this value so don't give it to me".
Now when you were initialising your pointers, you were doing:
double *estimate, *min = 0;
This only sets min to the null pointer. Since estimate is left uninitialized, you can't rely on its value being null. You need to provide an initialiser for each declarator:
double *estimate = 0, *min = 0;
Thanks to #sftrabbit. The problem was the initialization. instead of
int freq,rows,cols=0;
The change was
int freq=0,rows=0,cols=0;
this removed the segmentation fault. Thanks a lot for your help :).
Since you are in a Linux environment, you can use valgrind to find out exactly where the segmentation fault is happening. Just type valgrind before the name of the program, or the way you execute your program. For example, if you execute your program with the following command:
hello -print
issue the following command instead:
valgrind hello -print
I see you already solved this one, but this may be helpful in the future!

topological sorting using dfs

here is topological sorting using DFS in c++,which has bugs(out of bound error)
#include<iostream>
#include<stdio.h>
using namespace std;
int count=0;
static int *a=new int[8];
void dfs(int u,bool v[],bool matrix[][8])
{
v[u]=true;
for(int i=0;i<8;i++)
if(!v[i]&& matrix[u][i])
dfs(i,v,matrix);
a[count++]=u;
}
int main()
{
bool v[8];
bool matrix[8][8];
matrix[7][6]=true;
matrix[0][1];
matrix[1][2]=true;
matrix[2][3]=true;
matrix[3][4]=true;
matrix[2][5]=true;
for(int i=0;i<8;i++)
if(!v[i])
dfs(i,v,matrix);
for(int i=0;i<8;i++)
cout<<a[7-i]<<" ";
}
please help me to fix this error,i think i should create matrix[8][2],but how to continue after that?
I have done a few changes and now your program finishes successfully on ideone
The most significant change is that you did not initialize matrix and v(even without this change the program still finished successfully but the output was only 0-s). I did not see the error you are talking about. The reason for getting only 0-s when you did not initialize v is obvious - all the values where non-zero and so all nodes where considered not visited.
EDIT: I also changed line 27 where you seemed to have forgotten " = true;"
EDIT 2: you are not freeing the memory for a which is not good. Also I don't see why you need dynamic array for a. You know its size aforehand. And one last remark - if you make the arrays matrix and v global they will get zeroed automatically(I am not saying that this is good approach just pointing out), but as they are local they are not zeroed.