Program Crash

When I attempt to compile my program, my program crashes. I'm pretty sure the shuffle_array function causes it to crash. When I delete the function and run the program, it compiles just fine and gives me an output. Just need a point in the right direction.

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
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void initialize_array(int[], int);
int * shuffle_array(const int[], int);
void print_array(const int[],int);

int main() {
	int size;
	int *initArray = nullptr;
	srand(time(0));
	cout << "Please enter an integer between 1-52 (inclusive): ";
	cin >> size;

	while (size < 1 || size > 52) {
		cout << "ERROR: Enter an integer 1-52 (inclusive): ";
		cin >> size;
	}

	initArray = new int[size];
	initialize_array(initArray, size);

	cout << "Original array is: ";
	print_array(initArray, size);

	initialize_array(initArray, size);

	int *shuffle = shuffle_array(initArray, size);
	cout << "Shuffled array is: ";
	print_array(shuffle,size);


	return 0;
}

void initialize_array (int firstArray[], int amount) {
	for (int index = 0; index < amount; index++) {
		firstArray[index] = index;
	}
}

int * shuffle_array(const int firstArray[], int amount) {
	int *shuffleArray = new int [amount];
	for (int index = 0; index < amount; index++) {
		shuffleArray[index] = firstArray[index];
		cout << shuffleArray[index] << " ";
	}
	for (int index = amount - 1; index >= 0; index--) {
		int j = rand() + (index + 1);
		int temp = shuffleArray[j];
		shuffleArray[j] = shuffleArray[index];
		shuffleArray[index] = temp;
	}
	return shuffleArray;
}

void print_array (const int firstArray[], int amount) {
	cout << "[ ";
	for (int index = 0; index < amount; index++){
		cout << firstArray[index] << " ";
	}
	cout << "]" << endl;
}

Last edited on
I've not the time to read it, but memory leaks don't cause crashes that easily, they are more something that uses resources while you're not aware of. Most of the times when you have a memory leak you won't even know it unless your program runs for hours and hours and you find out that ram usage actually inreased more than it should have had.
I'll edit the post then, but when I get rid of the shuffle_array function, the program doesn't crash. So I'm confused on what it could possibly be.
Last edited on
On lines 50ish, you seem to make your program access random indexes of an array, even if they may be out of bounds. That's quite dangerous and will cause leaks.
I'm an idiot. Thank you very much fifi885. Realized I accidentally put
int j = rand() + (index + 1);
instead its supposed to be modulus. WOWZERS
Topic archived. No new replies allowed.