Asa Hunt Asa Hunt - 3 months ago 16
C Question

Correcting this segmentation fault

I'm working through this example in C and my Debian(64-bit Kali) distribution keeps saying this causes a segmentation fault and won't run it. I'd like to fix this so I can run it and keep learning assembly. Here's my command:

gcc -ggdb -mpreferred-stack-boundary=2 -fno-stack-protector -o Simple SimpleDemo.c


Source:

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

int add(int x, int y)
{
int z =10;

z = x + y;
return z;
}

main(int argc, char **argv)
{
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int c;
char buffer[100];

gets(buffer);
puts(buffer);

c = add(a,b);

printf("Sum of %d+%d = %d\n",a, b, c);
exit(0);
}

Answer

Did you supply two arguments? The program needs them, but does not check they exist. If you run the program with no arguments, that will probably cause a segfault.

If this was a serious example I would throw away the book and look elsewhere. The main() function has no return type. It does not check for program arguments. It has a superfluous buffer read and write. It uses exit() where it is normal to use return. The function add() assigns a value to z before over writing it. Here is the code cleaned up, but it would still be better to use strtol() than atoi().

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

int add(int x, int y)
{
    int z = x + y;
    return z;
}

int main(int argc, char **argv)
{
    int a, b, c;
    if (argc < 3)
    {
        printf ("Need two arguments\n");
        return 1;
    }
    a = atoi(argv[1]);
    b = atoi(argv[2]);
    c = add(a,b);
    printf("Sum of %d+%d = %d\n",a, b, c);
    return 0;
}