Eigen Expression Debugging - c++

I'm debugging a function that does some math with the Eigen library and am getting different results on different platforms. I don't see anything obviously wrong but I'm really not that familiar with the library. I've pulled the local variables out into a simple test application. hitRight ends up true on Mac and Windows but not on Linux. While debugging I figured out that putting .eval() at the end of the "auto rightDistance" line resolves the problem but I'd really like to understand why.
#include <stdio.h>
#include "eigen/Eigen/Core"
using namespace Eigen;
int main()
{
Vector2i p = Vector2i(302,12);
int mTabControlWidth = 20;
Vector2i mPos = Vector2i(0,0);
Vector2i mSize = Vector2i(310,24);
auto rightDistance = (p - (mPos + Vector2i(mSize.x() - mTabControlWidth, 0))).array();
bool hitRight = (rightDistance >= 0).all()
&& (rightDistance < Vector2i(mTabControlWidth, mSize.y()).array()).all();
if (hitRight)
printf("Hit Right\n");
printf("Hit none\n");
return 0;
}

Vector2i(mSize.x() - mTabControlWidth, 0) gets destructed at the next ;, while rightDistance still refers to it. That is undefined behavior, i.e., with some luck it works like you expect, but it might do whatever the compiler wants to do (most likely crash or return arbitrary results).
As Avi said, just avoid the auto. In your case, you should also use Array2i instead of Vector2i. This saves you from writing all the .array().
Also, if the auto expression worked, rightDistance would be evaluated twice instead of once (o.t.o.h, compiler are usually good at optimizing that away).
int main()
{
Array2i p(302,12);
int mTabControlWidth = 20;
Array2i mPos(0,0);
Array2i mSize(310,24);
Array2i rightDistance = (p - (mPos + Array2i(mSize.x() - mTabControlWidth, 0)));
bool hitRight = (rightDistance >= 0).all() && (rightDistance < Array2i(mTabControlWidth, mSize.y())).all();
if (hitRight)
printf("Hit Right\n");
printf("Hit none\n");
return 0;
}

Related

use of 'n' before deduction of 'auto' C++

I'm trying to have my function return 3 values (n, down and across) I've read online how 'auto' can be used but must be doing something wrong.
The function takes in a 2D vector of integers (as well as other variables) and checks for how many numbers are connected to board[0][0] such that they are the same number.
I've tried putting auto in front of the function inside the function itself, tried leaving it blank, tried just having chain = chainNodes(...) but I always seem to get an error. Here's the code:
tuple<int, int, int> chainNodes(vector<vector<int>> board, int originalNum,
unsigned int across, unsigned int down, int ijSum,
int n)
{
struct chain {
int n, down, across;
};
if(down + across > ijSum) {
ijSum = down + across;
} else if((down + across == ijSum) &&
((down - across) * (down - across) < (ijSum) * (ijSum))) {
ijSum = down + across;
}
board[down][across] = 0;
n += 1;
// Check below
if((down != (board.size() - 1)) && (board[down + 1][across]) == originalNum) {
down += 1;
auto [n, iPoint, jPoint] = chainNodes(board, originalNum, across, down, ijSum, n);
down -= 1;
}
// Check right, up and left (I've removed so its not too messy here)
return chain{n, down, across};
}
Sorry, I forgot to include the error message.
error: use of 'n' before deduction of 'auto'
It occurs on the line that uses auto.
Issue with
auto [n, iPoint, jPoint] = chainNodes(board, originalNum, across, down, ijSum, n);
is similar to
auto n = foo(n); // `foo(n)` uses `n` from `auto n`,
// not the one from outer scope as function parameter
The construct int a = a + 1; is legal but lead to UB as reading uninitialized variable.
That kind of construct allows legal and valid behavior void* p = &p;.
Your code has other errors and it is not clear for me expected behavior of the function.
So not sure if following is the correct fix, but you might want:
n = std::get<0>(chainNodes(board, originalNum, across, down, ijSum, n));

Try to reduce execution time but fail

Assume there is a set of points and almost every points are inside a quadrilateral. But a few are not. I want to know which points are not inside the quadrilateral.
So the function looks like this.
bool isInside(Point a, Point b, Point c, Point d, Point p) // a,b,c,d are the points consist of the quadrilateral.
{
if(orientation(a, b, p) < 0)
return false;
else if(orientation(b, c, p) < 0)
return false;
else if(orientation(c, d, p) < 0)
return false;
else if(orientation(d, a, p) < 0)
return false;
else
return true;
}
I wanted to reduce the number to call the orientation function and the orientation function looks like.
int orientation(const Point& p, const Point& q, const Point& r)
{
double val = (q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x);
if (val == 0)
return 0; // colinear
return (val < 0) ? -1 : 1; // right or left
}
So I modified the function isInside like this.
bool isInside(Point a, Point b, Point c, Point d, Point p)
{
int result;
if(p.x <= b.x)
{
result = orientation(a, b, p);
}
else
{
result = orientation(b, c, p);
}
if(result == -1) return false;
if(p.x <= d.x)
{
result = orientation(a, d, p);
}
else
{
result = orientation(d, c, p);
}
return (result == -1) ? true : false;
}
By this, the number of calling the orientation function reduces almost half(if there are more than 100,000 points it is a huge amount of number). However, it seems it does not affect the time taken and sometimes takes more.
I don't know how come this happens even though it reduces a lot of function calls.
Compiler Optimizations
It would be a good idea to check whether or not you are building with optimizations enabled. If you are building your application in debug mode, the compiler may not be optimizing your code. If you are, try running in release mode. It may build your application with optimizations enabled, or a higher level of optimization. This way, you can potentially leave your code as is, with little worrying about optimizing your code (Unless fast performance is absolutely necessary).
Quatitative Results
You could also add test code, that will allow you to get quantitative performance results (Running function x() n times takes m seconds, so each x() call takes m divided by n seconds). Then, you should be able to figure out which block of code is taking the most time.
An example of how you can go about doing the above (Without writing it for you) would look like:
#include <iostream>
#include <chrono>
//Doesn't matter where it is called, just using main as an example
int main(int argc, char *argv[])
{
int numRuns = 1000000; //Or passed in to allow changing # of runs
//without rebuilding: int numRuns = atoi(argv[1]);
//Code to initialize Point a, b, c, d, and p.
high_resolution_clock::time_point orien_start_time = high_resolution_clock::now();
for(int i = 0; i < numRuns; ++i)
{
orientation(a, b, p); //Ignore the return value
}
high_resolution_clock::time_point orien_end_time = high_resolution_clock::now();
high_resolution_clock::time_point orien_start_time = high_resolution_clock::now();
for(int i = 0; i < numRuns; ++i)
{
isInside(a, b, c, d, p); //Ignore the return value
}
high_resolution_clock::time_point orien_end_time = high_resolution_clock::now();
//Format and print/log the results
}
Then, with those time points, you can calculate how long each function takes to run. You can then use these numbers to pinpoint where exactly your application is slowing down. Going this route, you can test your old implementation vs. your new implementation, and see if the new way is infact faster. You could even try different sets of Points, to see if that changes application performance (For example, try both functions with points p1 through p5, then try both again with p6 through p10).
Note: There are a lot of things that can effect application performance outside of the code you write, which is why I used one million for the hard coded numRuns. If you go with a small number of iterations, your execution time per function call can swing pretty drastically depending on what else is running on your system. My recommendation for gathering quantitative results would be to run the test(s) on a freshly rebooted system where your application is the only user process running, that way it doesn't have to share as many resources with other applications.

incompatible implicit declaration of built-in function 'malloc'

My program is
#include <iostream>
char * grabNumber ( char * begin )
{
// Interpret *begin as the start of a double and add the characters to a
// string retstr
char * begincpy = begin;
int foundDot = 0;
while ((*begin >= '0' && *begin <= '9') || *begin == '.')
{
if (*begin == '.')
{
if (foundDot == 0) foundDot = 1;
else break;
}
++begin;
}
long n = begin - begincpy; // # of characters parsed
char * retstr = malloc(sizeof(char) * (n + 1)); // string to be returned
for (long k = 0; k < n; ++k) retstr[k] = *begincpy++;
retstr[n] = '\0';
return retstr;
}
int main()
{
char str [] = "abc3.14def";
std::cout << grabNumber(str+3); // should print "3.14"
return 0;
}
and the errors I'm getting are
Line 20: warning: incompatible implicit declaration of built-in
function 'malloc' Line 21: error: 'for' loop initial declaration used
outside C99 mode
corresponding to the 2 lines
char * retstr = malloc(sizeof(char) * (n + 1)); // string to be returned
for (long k = 0; k < n; ++k) retstr[k] = *begincpy++;
See: http://codepad.org/c2tNGFEo
Also, is there a way that I can cut down on the redundancy of my algorithm, because it's checking for a . twice in each iteration of the while loop, and yet I can't think of a cleaner way to handle the fact that I need to stop the loop if we've run into a second .
I'm guessing you are trying to write C++ as you have included iostream and used std::cout. However the error message shows you are using a C compiler. I also guess that you wrote gcc myprogram.c. To get C++ compilation you either need to write g++ instead of gcc, or rename your file to have a .cc extension. (Preferably both).
To use malloc you need #include <cstdlib>.
Also you may need using namespace std; or using std::malloc; after that; and you will need to cast the value returned by malloc because C++ does not implicitly convert from void * to other pointer types.
However malloc is rarely used in C++ as it does not initialize non-trivial objects properly. Consider changing this code to:
char * retstr = new char[n+1];
then you won't need any extra includes.
But this is still a weak design as you are now relying on the caller to free the memory. In fact your main function has a memory leak as it does not free the memory.
In C++ it is better style to have memory managed by a container class that knows about memory management; so the programmer can't make any mistakes. (Incase you are wondering, this usually doesn't introduce any inefficiency and may even speed things up).
A much better approach would be to #include <string>, make the function return std::string, and change the last five lines of your function to:
return { begincpy, begin };
or if using a pre-C++11 compiler,
return std::string(begincpy, begin);
Let's start by observing that you are not writing C, you are writing C++. You should fix your compilation/project settings so you compile your files using the C++ compiler instead of the C compiler. This will fix the compilation error about the for loop also, as that is not valid in C before C-99.
Secondly, the first warning is actually due to a missing include. In C you would #include <stdlib.h> in C++ you'd #include <cstdlib> to get the definitions from the C standard library.

Values of the function parameters are changing randomly (but they're not modified from the code)

I have to implement an NBC (for finding clusters in the provided set of data) algorithm at my class project with a friend. We came across very strange issue. There are few helper functions, and the one with a problem is kNN (possibly kEN too) in the kNB.h file. After passing arguments to it from the main function of the program (for example k=3 and p=5), it goes to the kNN function and starts changing values of k and p randomly, even though function code is not supposed to do that anywhere as you can see below.
Also, while using debugging mode and going through this function step by step I noticed that it sometimes comes back before the first while which I think shouldn't happen. I guess it may be some trivial mistake, but I'm not very good at C++ (unfortunately we were ordered to use it). You can download entire Visual Studio 2013 solution from here: https://dl.dropboxusercontent.com/u/1561186/EDAMI.zip. So, does anyone have any idea why described situation is happening?
static vector<int> kNN(int k, int p, Dataset<V>* records)
{
int b = p, f = p;
bool backwardSearch, forwardSearch;
vector<int> tmp;
LengthMetric<V>* lengthMetric = records->getLengthMetric();
backwardSearch = PrecedingPoint(records, b);
forwardSearch = FollowingPoint(records, f);
int i = 0;
while (backwardSearch && forwardSearch && i < k)
{
if (records->getRecord(p)->getLength() - records->getRecord(b)->getLength() < records->getRecord(f)->getLength() - records->getRecord(p)->getLength())
{
i++;
tmp.push_back(b);
backwardSearch = PrecedingPoint(records, b);
}
else
{
i++;
tmp.push_back(f);
forwardSearch = FollowingPoint(records, f);
}
}
while (backwardSearch && i < k)
{
i++;
tmp.push_back(b);
backwardSearch = PrecedingPoint(records, b);
}
while (forwardSearch && i < k)
{
i++;
tmp.push_back(f);
forwardSearch = FollowingPoint(records, f);
}
return tmp;
}
Look at second constructor of your class Dataset
Dataset(vector<Record<V>*> rrecords,
LengthMetric<V>* metric = new DumbLengthMetric<V>())
: records(rrecords),
lengthMetric(lengthMetric) { // <-------------------
lengthMetric(lengthMetric) does nothing. Changing it to lengthMetric(metric) I got some result on your project and no one variable was changed.
BTW, do not include in zip any stuff like folders Debug, Release and files *.sdf, *.ncb

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!