Hari Krishna
Hari Krishna

Reputation: 3568

why gcc printing "Segmentation fault: 11"?

When I ran below program using gcc compiler, I end up in "Segmentation fault: 11", but when I ran the same at "https://www.onlinegdb.com/online_c_compiler", it is executing perfectly fine. I would like to know, why gcc is throwing segmentation fault here?

#include <stdio.h>

int main(){

    typedef int myArray[10];

    myArray x = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};//Equivalant to x[10]
    myArray y[2]; //equivalant to y[10][2]

    int counter = 0;

    for(int i = 0; i < 10; i++){
        for(int j = 0; j < 2; j++){
            //printf("%i %i\n", i, j);
            y[i][j] = counter++;
        }
    }

    printf("\n\nElements in array x are\n");
    for(int i = 0; i < 10; i++){
        printf("x[%i] = %i\n", i, x[i]);
    }

    printf("\n\nElements in array y are\n");

    for(int i = 0; i < 10; i++){
        for(int j = 0; j < 2; j++){
            printf("y[%i][%i] = %i\t", i, j, y[i][j]);
        }
        printf("\n");
    }

    return 0;
}

I am using gcc version 4.2.1. Operating System: MAC

$gcc --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/c++/4.2.1
Apple LLVM version 10.0.0 (clang-1000.10.44.4)
Target: x86_64-apple-darwin18.2.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

Upvotes: 2

Views: 143

Answers (1)

Sander De Dycker
Sander De Dycker

Reputation: 16243

The comment here is wrong :

myArray y[2]; //equivalant to y[10][2]

y is actually defined as :

int y[2][10];

ie. y has 2 rows of 10 int's each.

When you then access y[i][j] with row index i ranging from 0 to 9 and column index j from 0 to 1, you end up accessing the array out of bounds whenever i * ROW_SIZE + j (or i * 10 + j) is larger than or equal to ROW_SIZE * ROW_CNT (or 10 * 2).

For example, y[9][1] tries to access the 2nd value on the 10th row. But there are only 2 rows in y.

Trying to access an array out of bounds has undefined behavior. Undefined behavior means anything at all can happen, including appearing to run fine or crashing.

To fix your code, define y as follows (so it matches the comment) :

int y[10][2];

Upvotes: 5

Related Questions