Search code examples
cpointerssegmentation-faultcoredump

Debugging for hours, segmentation fault. Can't find the issue


Have some code that seems to work but all of a sudden I started getting a segmentation fault every time the code is ran.

Hoping a fresh pair of eyes could help me find the problem.

It runs this line (printf("There are %d arguments excluding (%s)\n", count-1, *(input));) And crashes after.

I've tried using the gdb and going over my code but I can't seem to find the problem.

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

int getDiff(char **list[], int n);
int getSum(char *list[], int n);

int main( int count, char *input[] )
{
    int total;

    printf("There are %d arguments excluding (%s)\n", count-1, *(input));

    if(strcmp(*(input+1),"sum") == 0){
                int i;
        for(i = 2; i<=count;){
            printf("%d ", atoi(*(input + 2)));
            i++;
            if(i < count){
                printf("+ ");
            }
        }
        total = getSum(input, count);
    }


    if(strcmp(*(input+1),"diff") == 0){
        total = getDiff(&input, count);
    }

printf(" === %d ====", total);


}

int getDiff(char **list[], int n){


    int i;
    int total = atoi(**(list + 2));
    for (i=3; i<= n;) {
        int convert;
        convert = atoi(**(list + i));
        total = total - convert;
        i++;
    }

return total;

}

int getSum(char *list[], int n){


    int i;
    int total = atoi(*(list + 2));
    for (i=3; i<= n;) {
        int convert;
        convert = atoi(*(list + i));
        total = total + convert;
        i++;
    }

    return total;

}

Should run and return a sum of integers that were converted from digits.

This is what the gdb tells me

Program received signal SIGSEGV, Segmentation fault. 0x00007ffff7b4c196 in __strcmp_sse42 () from /lib64/libc.so.6


Solution

  • The indices in getSum need some fixing. The input list is [0-program, 1-"sum", 2-"3", and 3-"4"]. And n=4. However, the sum look goes from 3 to 4 (including 4). There is no element #4 in list, which triggered the SEGV.

    Consider limiting the loop to i<n instead of i<=n.

    Style wise, move the i++ to the 'for' statement, declare variable and set them on the same line, and consider using indices, instead of pointer style references (list[i], instead of *(list+i). It will make the code easier to read, and hopefully, better grade!

    int getSum(char *list[], int n){
    
        int total = atoi(*(list + 2));
        for (int i=3; i< n; i++) {
            int convert = atoi(*(list + i));
            total = total + convert;
        }
    
        return total;
    
    }
    

    Last, consider fixing the printout of variables printf("%d ", atoi(*(input + 2)));. It duplicate the 2nd parameter, which is not what you want.