Reputation: 95
I'm running the following C code.
void manual_enter(int * state_count, char * states, char * alphabet, char * start_state, char * accept_states) {
int counter;
printf("Please enter the number of states in the DFA. ");
scanf("%d", state_count);
states = (char *) malloc(sizeof(char) * (*state_count) );
printf("\n!");
counter = 0;
for(counter = 0; counter < *state_count; counter++) {
printf("\n!");
printf("\nPlease enter state: %d", counter);
scanf("%c", states[counter]);
printf("%c", states[counter]);
}
return;
}
I receive a segfault after the 2nd exclamation point but before the prompt to enter a given state number. I ran in gdb to get a backtrace and this is what I got:
(gdb) bt
#0 0x00007fff8b313fda in ?? () from /usr/lib/system/libsystem_platform.dylib
#1 0x00007fff5fbff360 in ?? ()
#2 0x00007fff88db1fbb in __fread () from /usr/lib/system/libsystem_c.dylib
Backtrace stopped: frame did not save the PC
I'm a programming novice, so it may well be that I'm approaching this debugging this all wrong. Any help or tips for how to approach this would be much appreciated. Thanks!
Upvotes: 0
Views: 1354
Reputation: 781706
The argument corresponding to %c
in scanf()
has to be a pointer:
scanf(" %c", &states[counter]);
You should have gotten a compiler warning about this.
You should also put a space before %c
so it will skip over whitespace before reading the character. Otherwise, every other state
will contain a newline character.
I wonder why you're allocating states
when the function receives this as an argument. If the function is supposed to allocate the states
array itself and return it to the caller (like it does with state_count), the argument should be
char **states`. Then you would do:
*states = malloc(sizeof(char) * (*state_count));
All the other references to states
in the function will also need to be changed to *states
.
Upvotes: 2