I am relatively new to C programming and I am trying to make a delimiter checker, but for some reason every time I run my code and it gets my input to check for delimiters, it has a segmentation fault (core dumped) error.
Below is the code of the main program:
int
main (void)
{
char* mystring;
printf ("Please enter a string\n");
gets(mystring);
if (fsm(mystring))
{
printf ("All matched");
}
}
It seems like it never enters the subprogram fsm though, because I put in a printf right at the beginning of the subprogram and it never shows up. It does ask for my input though and prints it back out if I put the printf in the main program before the subprogram line.
Here is my prototype:
boolean fsm(char[]);
and here is the beginning of the subprogram if that is any help:
boolean fsm (char mystring[])
{
printf("here\n");
int counter = -1;
int state = 0;
c_stack top;
c_init_stack (&top);
while (1)
{
switch (state)
{
case 0:
counter = counter + 1;
if (is_open (*mystring))
state = 1;
else if (is_close (*mystring))
state = 2;
else if (mystring = '\0')
state = 3;
else
state = 4;
break;
You are trying to read into an uninitialized
char*. Just declaringchar *mystringdoesn’t give you a string to work with: you’ll need to allocate space for the string.Either:
Or:
Once you have a buffer, use
fgetsinstead ofgets.fgetsallows you to specify an upper-bound on the number of characters read, sofgetsalong with something likeMAX_STRING_LENyou’ll be able to accept only as much data as your buffer will hold.As it is, since C doesn’t initialize automatic (local) variables,
mystringhas an undefined value. It can point to any random part of memory. When you try togetsusing this memory location, you’re trying to write to that memory that doesn’t belong to you.Finally, this condition with a single
=:else if (mystring = '\0')is an assignment, and not an equality test.