My following code runs into error if I comment out the first line in the constructor. The return error is:
libc++abi.dylib: terminating with uncaught exception of type boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<std::overflow_error> >: Error in function boost::math::cyl_bessel_k<double>(double,double): numeric overflow
Abort trap: 6
However, it is weird that if I output something (e.g., uncomment the first line) in the constructor, then my program works fine.
GP::GP(const Training_set& _sample, Eigen::VectorXd& param,
const std::string& which_kernel) : sample(_sample)
{
// std::cout << "WORKS" << std::endl;
if (which_kernel == "Matern") {
std::cout << "Matern kernel is used!" << std::endl;
Kernel_Matern matern(param, param.size());
kernel = &matern;
} else if (which_kernel == "Square_Exponential") {
std::cout << "Square Exponential kernel is used!" << std::endl;
Kernel_SE se(param, param.size());
kernel = &se;
} else {
std::cout << "Cannot identify the kernel" << std::endl;
exit(1);
}
input_dim = sample.dim;
input_size = sample.size;
L_chol.resize(sample.size, sample.size);
Eigen::MatrixXd cov_matrix = Eigen::MatrixXd::Zero(sample.size, sample.size);
get_cov_matrix(sample.X, input_size, sample.X, input_size, cov_matrix);
get_chol(cov_matrix);
}
You are storing an address of a temporary that goes out of scope. Using *kernel after what it points to goes out of scope is undefined behavior.
kernel should be of type std::unique_ptr<X> instead of type X*.
Replace assignment with:
kernel = std::make_unique<Kernel_Matern>(param, param.size());
or:
kernel = std::make_unique<Kernel_SE>(param, param.size());
at the two lines in question.
If you have code where you pass kernel to a function, instead pass kernel.get().
Note that is blocks copying instances of GP but not moving them, as unique ptr is move-only. If you have a type that stores both values and pointers into its own values, copying it is probably a bug anyhow.
Related
I created decorator function to add functionality to existing functions. The program outputs correct function pointer addresses along with an elapsed time to iterate 10 x helloworld as expected.
Yet, if I change decorator function to take the original_function by value (FunctionPointer original_function), the program terminates with a segmentation fault, which I don't get the reason why it fails.
#include <iostream>
#include <chrono>
typedef void (*FunctionPointer)();
auto
decorator(FunctionPointer && original_function) // if changed to FunctionPointer original_function, it causes segmentation fault when the closure(lambda expression) is called later on
{
std::cout << "Decorator: " << (void*)original_function << std::endl; // 0x558072fb0b90
return [&]()
{
std::cout << "Decorator: " << (void*)original_function << std::endl; // 0x558072fb0b90 but 0x0 when original_function passed by value
auto t0 = std::chrono::high_resolution_clock::now();
original_function();
auto duration = std::chrono::high_resolution_clock::now() - t0;
std::cout << "\nElapsed " << duration.count() * 1000.0f << " ms\n";
};
}
void
helloworld(void)
{
for (auto i = 0; i < 10; i++)
std::cout << "Hello, World!\n";
}
int
main(void)
{
std::cout << "Main: " << (void*)helloworld << std::endl; // 0x558072fb0b90
auto my_helloworld = decorator(helloworld);
my_helloworld();
return 0;
}
The difference is that when you pass the function by value, the parameter passed into the lambda is a reference to the function parameter, which goes out of scope when decorator returns. When you later call the returned lambda, you reference this out of scope variable, which is Undefined Behavior.
It works when you pass by universal reference, the parameter passed to decorator is a reference, which is passed to the lambda. So it is still valid later when you call the lambda.
You may be able to change your lambda to pass by value (use [=]) to get the changed version to work.
Im having this really weird error during run-time.
My program takes two parameters, does some math calculus with them and std::cout's the values in the end.
My program works if i input somevalues, but if i input other values it says that a variable is being used without being initialized, which i think it makes no sence.
Here is the code:
#include <iostream>
#include <stdio.h>
#include <cmath>
double align_nb(int n) { return { ceil(n / 512.0)*512.0 }; } // bytes
double align_pt(int k) { return { floor(k / 512.0)*512.0 }; } // pointer
int main(int argc, char * argv[])
{
int o_n = std::atoi(argv[1]); // original number
int o_p = std::atoi(argv[2]); // original pointer
int max_bytes, new_pointer; // max bytes to read, new pointer to point
float log = (std::log(o_n) / std::log(2));
if (log != floor(log))
{
max_bytes = align_nb(o_n); // bytes alinhados para a frente
new_pointer = align_pt(o_p); // ponteiro alinhado atrĂ¡s
}
else if (log == floor(log))
{
new_pointer = align_pt(o_p);
if (max_bytes + (o_p - new_pointer) >max_bytes)
{
max_bytes += 512;
}
}
std::cout << "Original bytes= " << o_n << std::endl;
std::cout << "Original pointer= " << o_p << std::endl;
std::cout << "Max_bytes= " << max_bytes << std::endl;
std::cout << "new_pointer= " << new_pointer << std::endl;
return 0;
}
Here are the values i tested it and it crashed, giving me that run-time error:
2048 513
1024 500
here is one example of values were the code doesnt give me that error and the program works:
513 520
Here is a print of the error it gives me.
I'd really appreciate someone explaining me why it gives me that error/how to fix it.
Regardless, thanks!
(PS: math tag is included cause it could be the math in the program that is causing it to crash. If annyone thinks it shoudlnt be used in this question, let me know in the comments and ill remove it.)
(PS 2: the variable it complains when it gives me the run time error is 'max_bytes'.)
If your code takes the else path at line 17, then your code doesn't initialize max_bytes, but uses it afterwards. That's the problem.
Notes:
comparing calculated floating point values for equality usually a bad practice
you don't need the additional if at line 23.
Make sure that for each path your code takes the values of the variables you use are initialized. If you don't you get what is called Undefined Behaviour. There could be anything in an uninitialized variable.
int max_bytes;
....
....
expression_involving_max_byte <- Dangerous!
I'm actually very new to c++. I tried to write a function template, passing a parameter as reference.
While doing so I got a std::bad_alloc. So I also tried to pass it as value and even by pointer. I always got a std::bad_alloc, but I'm very sure, the object exists and the adress is correct (checked it with debugger).
My last try was to create the object right in the function. It works, if I use hard-coded data, but not if I pass the data, needed to create the object, as function parameter.
I'm using a specific framework for numeric simulation (http://www.dune-project.org/), so I'm not sure, if example code is helpfull. I just contacted the framework support and they had no idea, where this problem comes from.
I hope anyone could help me or has an idea, how to fix this/work arround!
code example:
template<const int dim, const int k>
int solvePoissonPDE2(int maxlevel, Dune::YaspGrid<dim>& grid)
{
/*
* Debugging Notes:
* function works, if grid, fieldvector, array AND bitset are created inside the function
* BUT NOT if grid OR the components used to create a grid are passed as reference, value or pointer parameters (SEGMENTATION FAULT)
*/
try {
/*// make grid
Dune::FieldVector<double, dim> L(1.0);
Dune::array<int, dim> N(Dune::fill_array<int, dim>(1));
std::bitset<dim> B(false);
Dune::YaspGrid<dim> grid(L, N, B, 0);*/
grid.globalRefine(maxlevel - 1);
// get view
using GV = typename Dune::YaspGrid<dim>::LeafGridView;
const GV &gv = grid.leafGridView();
const int q = 2 * k;
// make finite element map
using DF = typename GV::Grid::ctype;
using FEM = Dune::PDELab::QkLocalFiniteElementMap<GV, DF, double, k>;
FEM fem(gv);
BCTypeParam bctype;
// solve problem
using Constraints = Dune::PDELab::ConformingDirichletConstraints;
poisson_driver<GV, FEM, BCTypeParam, Constraints>(gv, fem, "poisson_yasp", bctype, false, q);
return 0;
}
catch (Dune::Exception &e){
std::cerr << "Dune reported error: " << e << std::endl;
return false;
}
catch (std::string &e){
std::cerr << "An error has been detected: " << e << std::endl;
return false;
}
catch (std::exception &e){
std::cerr << "STL reported error: " << e.what() << std::endl;
}
catch (...){
std::cerr << "Unknown exception thrown!" << std::endl;
return false;
}
}
all used functions are working and are tested.
I'm trying to build a lambda that wraps some input functions with some pre/post actions.
My code works fine and pre/post actions get called correctly if I try to wrap a regular function/lambda.
However, when I try to apply my decorating lambda to a function that it produced before, my program crashes after complaining that the inner function was freed at some point (this is confirmed by valgrind).
What puzzles me is that the crash depends on the compiler: the code works perfectly fine with Xcode 6 clang (clang-3.6 based), but crashes on linux using clang++-3.6 and g++4.8.4.
I've made a small program that reproduces the behaviour:
#include <iostream>
#include <string>
#include <functional>
using namespace std;
typedef function<void(void)> NestedFn;
int main()
{
// Create a cfunction
auto lambdaFactory = [&](string title, NestedFn nestedFunc)
{
// title is copied to the new lambda
return [&, title]() {
cerr << "------------ START -----------" << endl;
cerr << "Inside: " << title << endl;
nestedFunc();
cerr << "------------- END ------------" << endl;
};
}
auto l1 = lambdaFactory("1", []() { cerr << "\tNest (1)" << endl; });
auto l2 = lambdaFactory("2", []() { cerr << "\tNest (2)" << endl; });
l1(); // Works ok, displays, START, 1, END
l2(); // Same here
auto dobble = lambdaFactory("Dobble", l1);
dobble(); // Display START, Inside Dobble, START,
// then crashes when trying to execute nestedFunc(), ie l1()
}
What did I get wrong in the variable scope management ? And is there any reason for this program not crashing using Apple's LLVM ?
EDIT
For the record, here is the correct lambdaFactory after the correction suggested by T.C. :
auto lambdaFactory = [&](string title, NestedFn nestedFunc)
{
return [&, title, nestedFunc]() {
cerr << "------------ START -----------" << endl;
cerr << "Inside: " << title << endl;
nestedFunc();
cerr << "------------- END ------------" << endl;
};
};
The lambda returned by a call to lambdaFactory captures nestedFunc by reference, but nestedFunc is a function argument passed by value, so it goes out of scope as soon as the call to lambdaFactory returns, resulting in a dangling reference.
And is there any reason for this program not crashing using Apple's LLVM ?
Undefined behavior is undefined. You are also likely using two different standard library implementations (libc++ on Mac/libstdc++ on linux), so there are likely differences in how everything is laid out etc.
I'd like to simulate a std::vector that has mixed const and non-const elements. More specifically, I want to have functions that operate on a vector and are allowed to see the entire vector but may only write to specific elements. The elements that can and cannot be written will be determined at runtime and may change during runtime.
One solution is to create a container that holds an array of elements and an equal sized array of booleans. All non-const access would be through a function that checks against the boolean array if the write is valid and throws an exception otherwise. This has the downside of adding a conditional to every write.
A second solution might be to have the same container but this time write access is done by passing an array editing function to a member function of the container. The container member function would let the array editing function go at the array and then check that it didn't write to the non-writable elements. This has the downside that the array editing function could be sneaky and pass around non-const pointers to the array elements, let the container function check that all is well, and then write to non-writable elements.
The last issue seems difficult to solve. It seems like offering direct writable access ever means we have to assume direct writable access always.
Are there better solutions?
EDIT: Ben's comment has a good point I should have addressed in the question: why not a vector of const and a vector of non-const?
The issue is that the scenario I have in mind is that we have elements that are conceptually part of one single array. Their placement in that array is meaningful. To use vectors of const and non-const requires mapping the single array that exist in concept to the two vectors that would implement it. Also, if the list of writable elements changes then the elements or pointers in the two vectors would need to be moved about.
I think you can accomplish what you wish with the following class, which is very simplified to illustrate the main concept.
template <typename T>
struct Container
{
void push_back(bool isconst, T const& item)
{
data.push_back(std::make_pair(isconst, item));
}
T& at(size_t index)
{
// Check whether the object at the index is const.
if ( data[index].first )
{
throw std::runtime_error("Trying to access a const-member");
}
return data[index].second;
}
T const& at(size_t index) const
{
return data[index].second;
}
T const& at(size_t index, int dummy) // Without dummy, can't differentiate
// between the two functions.
{
return data[index].second;
}
T const& at(size_t index, int dummy) const // Without dummy, can't differentiate
// between the two functions.
{
return data[index].second;
}
std::vector<std::pair<bool, T> > data;
};
Here's a test program and its output.
#include <stdio.h>
#include <iostream>
#include <utility>
#include <stdexcept>
#include <vector>
//--------------------------------
// Put the class definition here.
//--------------------------------
int main()
{
Container<int> c;
c.push_back(true, 10);
c.push_back(false, 20);
try
{
int value = c.at(0); // Show throw exception.
}
catch (...)
{
std::cout << "Expected to see this.\n";
}
int value = c.at(0, 1); // Should work.
std::cout << "Got c[0]: " << value << "\n";
value = c.at(1); // Should work.
std::cout << "Got c[1]: " << value << "\n";
value = c.at(1, 1); // Should work.
std::cout << "Got c[1]: " << value << "\n";
// Accessing the data through a const object.
// All functions should work since they are returning
// const&.
Container<int> const& cref = c;
value = cref.at(0); // Should work.
std::cout << "Got c[0]: " << value << "\n";
value = cref.at(0, 1); // Should work.
std::cout << "Got c[0]: " << value << "\n";
value = cref.at(1); // Should work.
std::cout << "Got c[1]: " << value << "\n";
value = cref.at(1, 1); // Should work.
std::cout << "Got c[1]: " << value << "\n";
// Changing values ... should only work for '1'
try
{
c.at(0) = 100; // Show throw exception.
}
catch (...)
{
std::cout << "Expected to see this.\n";
}
c.at(1) = 200; // Should work.
std::cout << "Got c[1]: " << c.at(1) << "\n";
}
Output from running the program:
Expected to see this.
Got c[0]: 10
Got c[1]: 20
Got c[1]: 20
Got c[0]: 10
Got c[0]: 10
Got c[1]: 20
Got c[1]: 20
Expected to see this.
Got c[1]: 200