"Segmentation Core Dumped" Not Using Pointers

I'm writing a program to create a 2D vector and randomly populate it with 1's and -1's. I'm attempting to use classes because I think later it will help a lot. Inside of main I have the user enter three variables two constants and the length of vector to be populated. Based on setting up flags in the program it seems like the "segmentation core dump" happens after I ask the user for the variable L in main.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <math.h> //sqrt
#include <stdlib.h>     /* srand, rand */
#include <vector> 
#include <ctime>


using namespace std;

class isingLattice {
	public:
	double H;
	double J;
	int length;
	vector< vector <int> > lattice;
	double energy();
	double magnetization();
	void makeLatticeConstant(double,double,int);
} actLattice;

double isingLattice::energy()
{
	double neighborSum=0;
	double totalSum=0;
	for (int i=0; i<length;i++)
	
		for (int j=0;j<length;j++)
		{
		neighborSum+=-J*lattice[i][j]*(lattice[(i+1)%length][j]+lattice[(i-1)%length][j]+lattice[i][(j+1)%length]+lattice[(i+1)%length][j]);
		totalSum+=-H*lattice[i][j];
		}
	
	return totalSum+neighborSum;
}

double isingLattice::magnetization() 
{
	double mSum=0;
	for (int i=0; i<length;i++)
		
			for (int j=0;j<length;j++)
			{
			mSum+=lattice[i][j];
			}
	return mSum;
}


void isingLattice::makeLatticeConstant(double x,double y,int L)
{
	H=x;
	J=y;
	length=L;
	lattice.resize(L);  // resize top level vector
	for (int i = 0; i < L; i++)
	{
    lattice[i].resize(L);  // resize each of the contained vectors
	}
	for (int c=0;c<L;c++)
		for (int j=0;j<L;j++)
		{
				lattice[c][j]=2*((rand()%2)-(1/2));
		}
	
}


int main()
{
	srand(time(0));
	
	isingLattice actLattice;
	double H,J;
	int L;
	cout << "Enter H, J, and the length of the lattice L:  " << endl;
	cin >> H;
	cin >> J;
	cin >> L;
	actLattice.makeLatticeConstant(H,J,L);
	cout << "energy is:  " << actLattice.energy();
	cout << "magnetization is:  " << actLattice.magnetization();
	return 0;
}
	
Line 62 looks wrong. 1/2 is always 0 due to integer division. I think you want 2*(rand()%2) -1.

As for the crash, it's probably at line 29 but I'm not certain. Try running the code in a debugger to see where it crashes. Note that (1) the first time through the loop you're computing (-1)%length and (2) you have latttice[(i+1)%length][j] in the expression twice.
Topic archived. No new replies allowed.