I am working on a program which generates a segmentation fault and I cannot understand why. If I remove the pointer declaration from "lowest" and "largest" variables and use them as pointerless integers the program works fine.
However, as soon as I try to use pointers, problems arise and I receive a segmentation fault. I realize that this is probably a very easy and well addressed issue, but I've tried to understand the code by looking on other similar problems. I haven't found a solution for my problem yet. Nor do I understand what's going wrong.
This is the code generating the problem (link to full source is below):
cout << "This is the array containing the random numbers:\n";
for(int *i=numbers; i != numbers + arrLength; i++) {
if((*i % 200) == 0 && *i > 200) {
cin.get();
cout << endl;
}
else
cout << *i << ' ';
// Get statistics
// In the continuation of getting, lowest, largest then adding to sum.
// THIS PART IS MAKING SEGMENTATION FAULT.
if(*i < *lowest)
lowest = i;
if(*i > *largest)
largest = i;
sum += *i;
}
The i variable points to an old reference which is declared after user input:
cout << "You entered: " << arrLength << "\n\n";
int *numbers = new int[arrLength];
// Fill the array with random numbers
srand(time(NULL));
int x;
int range = 5001;
for(int index=0; index<arrLength; index++){
*(numbers + index) = rand() % range;
x = rand() % 2;
if(x > 0) {
*(numbers + index) = *(numbers + index) * -1;
}
}
Please explain to be why my program isn't working and what I am doing wrong. As I've said earlier everything works except the:
if(*i < *lowest)
lowest = i;
if(*i > *largest)
largest = i;
Full source: http://pastie.org/2105963
Thanks in advance on this matter!
int *largest = 0, *lowest = 0, sum = 0;
This is your problem. You never allocate memory or assign a valid address to these. And when you dereference a NULL pointer, like here
if(*i < *lowest) //lowest is NULL
you get Undefined Behavior, which includes segmentation fault, nasal demons, and anything else
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With