vl_stackoverflow vl_stackoverflow - 3 months ago 35
C++ Question

Pointer arithmetics. core dumped

This is my small code. It works fine until dim=3. If I enter dim=4 I get this strange error:

makefile:10: recipe for target 'exec' failed
make: *** [exec] Aborted (core dumped)

I think "core dumped" appears when I try to access memory which I do not own but I cant see where the mistake is in this code.

1 #include <iostream>
2
3 using namespace std;
4
5 int main(){
6 int dim = 0;
7 double* y = new double[dim+1];
8 double* x = new double[dim+1];
9
10 do{
11 cout << "Enter a dimension:\n";
12 cin >> dim;
13 if(dim<=0) cerr << "Error: Dimension is lower equal 0!\n";
14 }while(dim<=0);
15
16 for(int i = 0; i<dim; i++){
17 *(y+i) = dim*i + 7;
18 *(x+i) = dim*i + 1;
19 cout << "*(y+" << i << "): " << *(y+i) << "\t" << "*(x+" << i << "): " << *(x+i) << endl;
20 }
21
22
23
24 delete[] y;
25 delete[] x;
26 return 0;
27 }

Answer

Let me explain what is wrong with your code:

int dim = 0;
double* y = new double[dim+1];
double* x = new double[dim+1];

x and y point to a single element because new double[0 + 1]

Then you ask the user to enter the dimensions. Once the user enters the dimensions your code breaks because you are trying to dereference a pointer that points to an invalid location. This is called undefined behavior. To fix this issue you have to first ask the user to enter the dim value and then allocate the appropriate space.

Comments