Segmentation Fault: 11

I get a segmentation fault, I do not understand why. Checked my code seems fine... Trying to get the reverse order of a list of numbers that I put in an array.

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
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{

    int size, a;
    int array[size];
    cin >> size;

    for (int i = 0; i <= size - 1; i++)
    {
        cin >> a;
        array[i] = a;
        cout << array[i];
    }

    for (int i = size-1 ; i >= 0; i--)
    {
        cout << array[i];
    }

    return 0;
}


Here the sample input I put.
SAMPLE INPUT

4
1 4 3 2



Here the sample output I'm looking for but I do not get. I get "Segmentation fault: 11" instead
SAMPLE OUTPUT

2 3 4 1
Last edited on
On line 12 size is unknown. So move line 12 after line 13.

Variable length array are normaly not allowed in c++.
Related question. At times I have seen "Segmentation fault", but when I attempt a stack trace using gdb, and then typing in "st" at the resulting prompt, what does the message "Nothing on stack" mean? Sure, it means nothing on stack to trace, but why would that happen? I am guessing one reason would be that the compilation or the execution failed even prior to anything being placed on stack .... is that possible?
it means nothing on stack to trace, but why would that happen?
It is possible that the stack is corrupt. One way to corrupt a stack is using extensive variable length arrays. Another is infinite recursion.

the execution failed even prior to anything being placed on stack .... is that possible?
Yes, that's possible. For instance when the initialization of a global variable causes a segmentation fault.
Topic archived. No new replies allowed.