Calling grad() of uninitialized std::math::var causes segmentation fault

The following obviously wrong code produces a segmentation fault on Ubuntu 16.04 gcc 5.4.
Have to set O = 0.0, of course. In the future maybe somebody also forget to initialize and
this maybe results in hard to detect behavior.

#include <cmath>
#include <stan/math.hpp>

int main() {
  stan::math::var m = 0.1;
  stan::math::var O;
  O -=  m;
  O.grad();
                                     
  return 0;
}
1 Like

That behavior’s not ideal, but it’s intentional. This problem in general is why I don’t like mutable objects that aren’t always guaranteed to be in a usable state.

To initialize requires allocation on the stack, and we don’t want to do that until necessary.

The functors like gradient encapsulate all the behavior so you don’t have to work with raw autodiff. You can follow the patterns they use to build your own, too, which will do the right thing with nesting, etc.