Home > Back-end >  Segmentation fault when there is just one value as input
Segmentation fault when there is just one value as input

Time:09-02

My code seems to be working fine, but I get a Segmentation fault when there is just one value as input. It should print a square shape based on a number as character input.

test case : ["2", "2"] "oo\noo\n" test case: ["", ""] "" test case : ["2"] SIGSEGV (signal 11)

#include <string.h>
#include <stdlib.h>

void my_square(int *x, int *y)
{
    int i , j;
    if (*x == 0 || *y == 0) {
        printf("");
    }
    else{
        for(i = 0; i < *x; i  ){
            for(j = 0; j < *y; j  ){
                if(*x<=2 && j == 0){
                    printf("o");
                }else if(*x<=2 && j == 1){
                    printf("o\n");
                }else if(*y<=2 && i == 0){
                    printf("o");
                }else if(*y<=2 && i == 1){
                    printf("o\n");
                }else{
                    //printf(" i: %d, j: %d ", i, j);
                    if(i == 0 && j == 0 || i == *y-1 && j == 0 || i == 0 && j == *x-1 || i == *y-1 && j == *x-1){
                        printf("o");
                    } 
                    
                    if(i >= 1 && j == 0 && i != *y-1) {
                        printf("|");
                    }
                    if(i >= 1 && j == *x-1 && i != *y-1) {
                        printf("|");
                    }
                    if(i == 0 && j >= 1 && j != *y-1|| i == *x-1 && j >= 1 && j != *y-1){
                        printf("-");
                    }
                    if(i >= 1 && j >= 1 && i < *x-1 && j < *y-1){
                        printf(" ");
                    }
                    if(j == *x-1){
                        printf("\n");
                    }
                
                }
            //printf("> %d, %d", i, j);
            }
        }
    }
}

int main(int ac, char **av)
{
    int x = atoi(av[1]);
    int y = atoi(av[2]);
    my_square(&x, &y);
    return 0;
}```

CodePudding user response:

You should always check ac before accessing av, otherwise it may lead to undefined behaviour (and cause a segmentation fault).

That's how you could do it (the first value is always the program file name):

int main(int ac, char **av)
{
    int x, y;
    if (ac <= 3)
    {
        x = atoi(av[1]);
        y = x; // if there's only one argument, we use it for both x and y

        if (ac == 3)
        {
            y = atoi(av[2]);
        }
        
        my_square(&x, &y);
    }

    return 0;
}
  •  Tags:  
  • c
  • Related