matplotlib-cpp icon indicating copy to clipboard operation
matplotlib-cpp copied to clipboard

Segmentation fault (core dumped) after successfully executing compiled file

Open abdusali1234 opened this issue 2 years ago • 1 comments

When I execute my compiled file, everything runs, but at the very end when everything has successfully ran, I get a segmentation fault. This happens after closing a figure or when a figure has been saved as an image. Here is my cpp file (I spent some time troubleshooting to get the plotting to work which is why I have that comment before plotting :p) :

#include <iostream>
#include <cmath>
#include <vector>
#include <iomanip>
#include "matplotlibcpp.h"

namespace plt = matplotlibcpp;

// Assumption: Data points are equidistant (same h)

void print_vec(std::vector<double> n){
  for (auto i : n){
    std::cout << i << std::endl;
  }
}

double forward_difference(std::vector<double> n, int i, double x_diff){
  double f_prime{};
  f_prime = (n[i + 1] - n[i]) / x_diff;
  return f_prime;
}

double backward_difference(std::vector<double> n, int i, double x_diff){
  double f_prime{};
  f_prime = (n[i] - n[i - 1]) / x_diff;
  return f_prime;
}

double central_difference(std::vector<double> n, int i, double x_diff){
  double f_prime{};
  f_prime = (n[i + 1] - n[i - 1]) / (2 * x_diff);
  return f_prime;
}

int main (){
  std::vector<double> x{};

  double h{0.1};

  // initialising x with data points
  for (double i = 0; i <= 10; i += h){
    x.push_back(i);
  };

  // display up to 3 decimal places
  std::cout << std::fixed;
  std::cout << std::setprecision(3);

  // get values for f(x) = sin(x) and f'(x) = cos(x)
  std::vector<double> sin_x{};
  std::vector<double> cos_x{};

  for (auto i : x){
    sin_x.push_back(std::sin(i));
    cos_x.push_back(std::cos(i));
  }

  // get the approximate derivative
  std::vector<double> approx_deriv{};

  for (int i = 0; i < x.size(); ++i){
    if (i == 0){
      approx_deriv.push_back(forward_difference(sin_x, i, h));
    }
    else if (i == x.size() - 1) {
     approx_deriv.push_back(backward_difference(sin_x, i, h)) ;
    }else {
      approx_deriv.push_back(central_difference(sin_x, i, h));
    }
  }

  // now it's time to plot the damn thing!
  
  plt::named_plot("sin(x)", x, sin_x);
  plt::named_plot("cos(x) (actual)", x, cos_x);
  plt::named_plot("cos(x) (approx)", x, approx_deriv, "k--");
  plt::legend();
  plt::save("h_01.png");
  //plt::show();  
  return 0;
}

Here is my Makefile:

num_diff: diff.cpp
	g++ diff.cpp -o numeric_differentiation -std=c++14 \
		-I/usr/include/python3.11 -lpython3.11

As mentioned before, the figures successfully display and show, its just the segmentation fault at the end. Is that something to be worried about?

abdusali1234 avatar Aug 16 '23 20:08 abdusali1234

Try to use plt::detail::_interpreter::kill(); after plt::show() this seems to fix this issue.

vincentgierisch avatar Sep 01 '23 16:09 vincentgierisch