Accessing array of structs causing segfault

Several of you helped me with this project a few days back. I got the code to compile thanks to your help, but now I'm running into a segfault. I've tracked down what code is causing it, but I have no idea how to fix it!

I've created an array of structs at global scope, (bad, I know. The instructor specifically said do it, or i'd try for a better solution,) and it works fine in int main() and the other functions where I'm using it. However, I've created a func to sort the array, and the function is causing a segfault. Upon further investigation, the first instance of accessing the array (whatever that happens to be) is causing the problem.
Edit: By way of clarification, I can read and write listCD[] without problems everywhere else in the code without a problem. It's only when I do this in listSort() that it causes a problem.

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
#define listSizeMax 100
struct albumDatabase {
	string title;
	string band;
} listCD[listSizeMax];

...
void listSort(albumDatabase[listSizeMax],int,char);

int main()
{
int i, listSize; // For the purpose of shortening this code fragment I'm not
                 //  showing where I set listSize, but it initializes correctly.
char selection,sortPrimary;
...
switch(sortPrimary)
{
case 't':
case 'T':
	cout << "Sorting database by song title...";
	listSort(&listCD[listSizeMax],listSize,'t');
	break;
case 'b':
case 'B':
	cout << "Sorting database by song title...";
	listSort(&listCD[listSizeMax],listSize,'b');
	break;
}
...
}

void listSort(albumDatabase listCD[listSizeMax], int length, char sortPrimary)
{
int indexSwap, index;
string temp[2];
cout << "\ndebug point #1" << endl; cout.flush();

for (index = 1; index < length; index++)
{

	cout << "\ndebug point #1.5" << endl; cout.flush();

	cout << listCD[0].title << endl; cout.flush();
	
	cout << "\ndebug point #2" << endl; cout.flush();

...   // This block contains an insertion sort algorithm. The next statement is
      //  an if statement with a monstrous test condition. I inserted the above
      //  three lines simply for debug. Execution core dumps after point 1.5,
      //  and never reaches point 2.
}
...
}
Last edited on
problem is in :
 
listSort(&listCD[listSizeMax],listSize,'t'); // You are just passing the address of the (garbage) element after the last index. 


change it to:
 
listSort(listCD,listSize,'t');


likewise for the next call.
Works like magic. Thanks!
Topic archived. No new replies allowed.