Aran Aran - 3 months ago 27
C Question

isdigit() Segmentation Fault

Getting a weird segmentation fault on following code when I try to pass a number into my application on command line.

int offset = 3;

int main(int argc, char *argv[]) {
// Check for arguments to see whether there is a custom offset
if (argc == 2) {
// If argc == 2 then we have a offset?
if (isdigit((unsigned char)*argv[1])) {
offset = atoi(*argv[1]);
printf("Offset changed to: %d\n", offset);
} else {
printf("Offset not changed due to %s not being a number.\n", *argv[1]);
}
} else if(argc >= 2) {
// If argc >= 2 then we have too many arguments
printf("Too many arguments.");
return 0;
}
}

Answer

argv[1] is already a string (of type char*), so writing *argv[1] dereferencing to the first byte which causes your segfault when passing that byte to atoi() and printf().

Fix it to:

offset = atoi(argv[1]);

and

printf("Offset not changed due to %s not being a number.\n", argv[1]);