0

In C++ I get a segmentation fault after telling the program how big the array should be (x).

Why is this happening and how do I fix this?

#include <iostream>
using namespace std;

int main()
{
    int x;
    cin >> x;
    int array[x];

    for (int *j=array; j; j++)
    {
        *j=0;
    }

    for (int *i=array; i; i++)
    {
        cin >> *i;
    }

    cout << array[3] << endl;
}
3dgoo
  • 15,716
  • 6
  • 46
  • 58
Joki
  • 23
  • 4

4 Answers4

2

Your loop conditions are wrong.

for (int *j = array; j; j++)

and

for (int *i=array; i; i++)

will not stop at the end of the array, as the condition j (i) is true when traversing the array (i.e., to be false, the pointer needs to be nullptr). In fact, pointer arithmetic past the array boundary plus one results in undefined behaviour. Your stopping condition should be

i < array + x;

Moreover, variable length arrays are an extension and not support by the C++ standard. Use new[] instead to allocate memory, as @Joshua Byer pointed out.

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • This is incorrect ... you well eventually run through all the positives and become 0 since it is like a int. – Joshua Byer May 06 '15 at 23:15
  • @JoshuaByer Not even sure if it is well defined behaviour... thanks anyway, corrected. – vsoftco May 06 '15 at 23:16
  • @vsoftco, It's undefined as soon as the pointer goes past the one-past-the-end position of the array, even without dereferencing it. – chris May 06 '15 at 23:42
0
int * array;
array= new int [x];

http://www.cplusplus.com/doc/tutorial/dynamic/

Joshua Byer
  • 524
  • 4
  • 11
0

Within a for statement, the second expression should terminate the loop by evaluating to false. In this case however you never terminate the loop:

for (int *j=array; j; j++)

Instead do:

for (int *j=array; j < array + x; j++)

The expression array + x (by pointer arithmetic) means one element past the end of the array.

The above goes for both of the loops.

olovb
  • 2,164
  • 1
  • 17
  • 20
0

The conditions used in your loops are incorrect.

eg. for (int *j = array; j; j++) even though j will eventually reach the end of the array but will still never evaluate to false (allowing the loop to finish). On top of this it means you will iterate to past the end of the array and move into Undefined Behaviour, this is probably why you are seeing the segfault.

you either need to do the following (super gross solution!!!! also not C++ standard supported):

for (int i = 0, *j = array; i < x; i++, j++)

which will increment a counter and check the array at the same time as incrementing your pointer.

OR USE VECTORS

std::vector is a much easier way to do what you are doing.

int arraySize;
cin >> arraySize;
std::vector<int> array(arraySize, 0);

for (int i=0; i < arraySize; i++)
{
    cin >> array[i];
}

cout << array.at(3) << endl;

Here is a live example.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175