czshfault

What is- zsh: segmentation fault in c programming and how to solve this fault?


I have got zsh: segmentation fault in this program and I don't know why. How run this program without this fault.

#include<stdio.h>
int main()
{
    int old[9]={'3','5','7','8','8','6','2','3','5'};
    int new[3][3], r, c, n;

    for (r=0;r<3;r++){
        for (c=0;c<3;c++){
            new[r][c]=old[n];
            n++;
        }
    }

    printf("New array is:\n");
    for (r=0;r<3;r++){
        for (c=0;c<3;c++){
            printf("%d",new[r][c]);
        }
        printf("\n");
    }
}

┌──(imsourobh㉿kali)-[~/Documents/codes/c/cse] └─$ cd "/home/imsourobh/Documents/codes/c/cse/" && gcc >array.c -o array && "/home/imsourobh/Documents/codes/c/cse/"array zsh: segmentation fault "/home/imsourobh/Documents/codes>c/cse/"array


Solution

  • Your problem is that the n variable is uninitialized. This means it's value is undefined, and using it to index an array is undefined behavior. Undefined behavior means anything can happen. Your program might have worked exactly as you planned.

    Or you might have gotten a segfault, which is what actually did happen.

    To avoid this, n should have been initialized to 0.

    As a sidenote, since n++ returns the value of n, then increments it, you could save yourself a line of code:

    new[r][c] = old[n++];
    

    Or you might avoid the need for n at all by using some math. Here I've defined constants for the dimensions of your two-dimensional array. I've also locally scoped r and c to their respective loops as they aren't needed outside of that scope. Lastly, I've used size_t rather than int.

    #include<stdio.h>
    
    #define ROWS 3
    #define COLS 3
    
    int main(void) {
        int old[] = {'3', '5', '7', '8', '8', '6', '2', '3', '5'};
        int new[ROWS][COLS];
    
        for (size_t r = 0; r < ROWS; r++) {
            for (size_t c = 0; c < COLS; c++) {
                new[r][c] = old[r * COLS + c];
            }
        }
    
        printf("New array is:\n");
    
        for (size_t r = 0; r < ROWS; r++) {
            for (size_t c = 0; c < COLS; c++) {
                printf("%d ", new[r][c]);
            }
    
            printf("\n");
        }
    }