c++arrayssegmentation-fault

Segmentation Fault: Zsh: segmentation fault ./a.out


I am new to coding and am getting this error message when I run my c++ program:

zsh: segmentation fault ./a.out

Here's the code:

#include <iostream>

using namespace std;

int main(){
    int i;
    int numElements;
    std::cout << "Enter the number of elements for the array: ";
    std::cin >> numElements;

    int myArray[numElements];
    std::cout << "Enter " << numElements << " numbers." << std::endl;

    for (i = 0; i < numElements; ++i) {
        std::cout << "Value: ";
        std::cin >> myArray[i];
    }

    for (i = numElements; numElements >= 0; --i) {
        std::cout << myArray[i] << " ";
    }

    return 0;
}

Here's the terminal with error message: enter image description here enter image description here

I tried adding a statement to print the array after the first for loop, but it did not display in the terminal. So the issue seems to be occurring at or before the first for loop.


Solution

  • You have bugs in you code.

    In particular your array printing loop is incorrect:

    for (i = numElements; numElements >= 0; --i) {
        std::cout << myArray[i] << " ";
    }
    

    There are 2 bugs in the above code:

    1. numElements >= 0 makes no sense. This conditition never changes, so the loop would run infinitely continuously decreasing i. When i gets negative values your code does an illegal thing and has so called undefined behavior. It may do whatever at this point, including launching a 3rd World War. But typically it will cause segmentation fault (and that's what it does). You want to compare i not numElements. But first check out point 2 below.
    2. on the first iteration you are accessing your array beyond its end: you are accessing the index i == numElements, while valid indices are: 0, 1, ... nuElements-1. numElements is beyond this arrays length. This is also an undefined behavior.

    PS. the code is not a valid C++. It's Gnu C++ extension and is not portable. Better use std::vector<int> for such cases.