I'm struggling with a small class I created. It is supposed to hold an array with data, that has to be deleted when the class object is deleted. Hence:
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <math.h> // for sin/cos
#include <algorithm> // for std::swap
class Grid
{
public:
unsigned int dimX_inner, dimY_inner;
double *x_vector1;
unsigned int ghostzone;
int dimX_total, dimY_total;
double h_x, h_y;
Grid(const unsigned int dimX_inner, const unsigned int dimY_inner, const unsigned int ghostzone = 0);
~Grid();
};
Grid::Grid(unsigned int gridsize_x, unsigned int gridsize_y, unsigned int ghostzoneWidth) : dimX_inner(gridsize_x),
dimY_inner(gridsize_y),
x_vector1(new double[(gridsize_x + 2 * ghostzoneWidth) * (gridsize_y + 2 * ghostzoneWidth)])
{
ghostzone = ghostzoneWidth;
dimX_total = gridsize_x + 2 * ghostzoneWidth;
dimY_total = gridsize_y + 2 * ghostzoneWidth;
h_x = (double)1.0 / (gridsize_x - 1);
h_y = (double)1.0 / (gridsize_y - 1);
}
Grid::~Grid()
{
delete[] x_vector1;
}
That's all I need for now. Added a little main:
int main()
{
int problemsize = 5;
Grid *grid1 = new Grid(problemsize, problemsize);
delete[] grid1;
return 0;
}
I've written a similar class before, that ran without problems. Granted most of it was taken from some online exercises/examples. But in this case I get a Segmentation fault when running the program (at the delete line). I guess it's the constructor, that somehow constitutes the problem. What I'd like to ask:
- What might be the cause of the segmentation fault?
- Is the constructor in the code "acceptable" (coding style wise)?
- Would I have to make any additional considerations when adding another data object to the class (e.g. an array *x_vector2)?
Short remark: I'm running this using WSL (don't know whether this is relevant)