How Do You Troubleshoot a C Program Displaying the Error “Segmentation fault” at Run Time?

Problem scenario
Your C program compiles.  But you get the error "Segmentation fault."  You expect the value of a variable to be printed.  How do you get the value to be printed without this error?

Solution
Does every print function print?  If one print function seems to be displaying the "Segmentation fault" error, look closely at the syntax thereof.  Here is a line that will produce this error:

   printf ("y is a %s\n", y);

Here is a similar but corrected line that will be error free:

  printf ("y is a %d\n",y);

The "%s" is appropriate for printing string variables.  For integer variables, use "%d" syntax.

Leave a comment

Your email address will not be published. Required fields are marked *