I am making a C program. I have a function that everything seems to be working great. But if I add another variable to it it suddenly does not work and I get a segmentation fault. (If I use gdb I get the error: Single stepping until exit from function __svfscanf_l,
which has no line number information. Program received signal: “EXC_BAD_ACCESS”.)
Here is my function:
void condition(char *command) {
printf("CAMMAND: %s\n", command);
char *cond;
char *expression;
char *file;
char *buffer;
buffer = malloc(200 * sizeof(char));
sscanf(command, "%s ( %s %s ) %[^\n]", cond, expression, file, buffer);
printf("COND: %s\n", cond);
printf("EX: %s\n", expression);
printf("File: %s\n", file);
printf("Command: %s\n", buffer);
if (!strcmp(expression, "checke")) {
printf("CHECK EXISTS\n");
if (file_exists(file)) {
printf("EXISTS\n");
}
} else if (!strcmp(expression, "checkd")) {
printf("CHECK DIR\n");
} else if (!strcmp(expression, "checkr")) {
printf("READ\n");
} else if (!strcmp(expression, "checkw")) {
printf("CHECK WRITE\n");
} else if (!strcmp(expression, "checkx")) {
printf("CHECK EX\n");
} else {
printf("NOOOO\n");
}
}
However, if I even change it to something like below I get an error. It seems to be failing at the sscanf call. But that works when I don’t add some variable.
void condition(char *command) {
int flag;
printf("CAMMAND: %s\n", command);
char *cond;
char *expression;
char *file;
char *buffer;
buffer = malloc(200 * sizeof(char));
sscanf(command, "%s ( %s %s ) %[^\n]", cond, expression, file, buffer);
printf("COND: %s\n", cond);
printf("EX: %s\n", expression);
printf("File: %s\n", file);
printf("Command: %s\n", buffer);
if (!strcmp(expression, "checke")) {
printf("CHECK EXISTS\n");
if (file_exists(file)) {
printf("EXISTS\n");
}
} else if (!strcmp(expression, "checkd")) {
printf("CHECK DIR\n");
} else if (!strcmp(expression, "checkr")) {
printf("READ\n");
} else if (!strcmp(expression, "checkw")) {
printf("CHECK WRITE\n");
} else if (!strcmp(expression, "checkx")) {
printf("CHECK EX\n");
} else {
printf("NOOOO\n");
}
}
Can’t seem to figure out why this is. Any help would be great!
You are getting memory corruption because you are passing pointers to characters, rather than pointers to character arrays, as the destination for
%sconversions.expression, as defined, is uninitialized and points to some random memory location. Here is the relevant part of thesscanfdocumentation:You need to allocate some space for
expressionetc.