Question

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;
Was it helpful?

Solution

You are trying to read into an uninitialized char*. Just declaring char *mystring doesn't give you a string to work with: you'll need to allocate space for the string.

Either:

char *mystring = malloc(MAX_STRING_LENGTH);

Or:

char mystring[MAX_STRING_LENGTH];

Once you have a buffer, use fgets instead of gets. fgets allows you to specify an upper-bound on the number of characters read, so fgets along with something like MAX_STRING_LEN you'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, mystring has an undefined value. It can point to any random part of memory. When you try to gets using 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top