Very odd segmentation fault/core dump.

This is a discussion on Very odd segmentation fault/core dump. within the C Programming forums, part of the General Programming Boards category; So I'm pulling out my hair here, as I can't figure this out. I'm getting a segmentation fault ( core ...

  1. #1
    Registered User
    Join Date
    Apr 2004
    Posts
    38

    Very odd segmentation fault/core dump.

    So I'm pulling out my hair here, as I can't figure this out. I'm getting a segmentation fault ( core dump) in my program and I don't understand why. It's a clean compile and when I run the program and it asks me for a valid choice, the scanf statement causes the seg fault. The code is below, but I'm totally baffled here.

    Code:
    void MenuOne ( int numStrings, char **strArray )
    {
       int i, inc = 1, userInput = 1, constant = 5;
    
       printf("\nMenuOne function opened. %d\n", numStrings );
    
    
          for ( i = 0; i < numStrings; i++ )
          {
                printf("strArray[%2d] - %s\n", i, strArray[i] );
          }
    
          printf ("Please select which string you'd like to analyze, or 0 to quit.\n");
          scanf ("%d", &userInput );
          printf("%d is the user's input\n", userInput);
    
          while( userInput < 0 ||  userInput > numStrings )
          {
             fprintf(stderr, "\nPlease enter a valid response. " );
             scanf("%d", &userInput );
          }
    
       MenuTwo ( userInput, strArray );
    }

  2. #2
    Welcome to the real world
    Join Date
    Feb 2004
    Posts
    50
    I just compiled and successfully executed your code and it works for me (although the array holds null values for me).

    Here is my output:

    MenuOne function opened. 5
    strArray[ 0] - (null)
    strArray[ 1] - (null)
    strArray[ 2] - (null)
    strArray[ 3] - (null)
    strArray[ 4] - (null)
    Please select which string you'd like to analyze, or 0 to quit.
    3
    3 is the user's input

    Are you sure the seg. fault is during the scanf call?

  3. #3
    Registered User
    Join Date
    Apr 2004
    Posts
    38
    I found I had a semicolon right after my for loop which was obviously a mistake, but that wasn't causing the seg fault. I have to think it's from that since it doesn't make it to my probe statement RIGHT after it.

  4. #4
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    Post your full source code, please, so we can compile and run it.
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  5. #5
    Registered User
    Join Date
    Apr 2004
    Posts
    38
    Here's my pal.c file
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    #include "pal.h"
    
    /* Display greeting message */
    /* name: PrintGreeting      */
    /* inputs: none             */
    /* returned value: none     */
    void PrintGreeting ()
    {
       printf( "\nWelcome to the Strings program.");
       printf( "\nThis program will allow you to anaylze any of the strings");
       printf( "\nfrom the input file in several different ways.");
       printf( "\n\nAlso: a palindrome is defined as any word or phrase that is");
       printf( "\nread the same way backwards and forwards.  For example, the word");
       printf( "\nracecar is a palindrome.");
    
    }
    
    /* Display instructions         */
    /* name: PrintInstructions      */
    /* inputs: none                 */
    /* returned value: none         */
    void PrintInstructions ()
    {
       printf( "\n\nTo use this program, simply select one of the strings you");
       printf( "\nwant to analyze, or 0 to quit.  After selecting a string");
       printf( "\na menu will appear which will enable you to test that string");
       printf( "\nin a number of different ways.  Select the corresponding");
       printf( "\nletter, or Q to quit.\n");
    }
    
    /* Reads in number of strings         */
    /* name: ReadNumStrings               */
    /* inputs: File pointer               */
    /* returned values: number of strings */
    int ReadNumStrings ( FILE *data )
    {
       int numStrings = 0;
       char buffer[101];
    
       while ( fgets ( buffer, 101, data ) != NULL )
       {
          numStrings++;
       }
    
       return numStrings;
    }
    
    /* Fills the array with the strings from the data file */
    /* name: FillArray                                     */
    /* inputs: File pointer, array of strings              */
    /* returned values: none                               */
    void FillArray ( FILE *data, char **strArray, int numStrings )
    {
       char buf[100];
       int counter = 0;
       int strLen;
       int i;
    
       rewind ( data );
    
       while ( fgets ( buf, 100, data ) != NULL )
       {
          strLen = strlen ( buf );
          strArray[counter] = (char *) malloc (strLen * sizeof (char));
          strcpy ( strArray[counter], buf );
          printf("%2d = %s\n", counter, strArray[counter]);
          counter++;
       }
    
       for ( i = 0; i < numStrings; i++ )
       {
          printf("strArray[%2d] = %s\n", i, strArray[i]);
       }
    
       printf("\nBeginning MenuOne function\n");
       MenuOne ( numStrings, strArray );
    }
    
    /* Controls the first level menu                 */
    /* name: MenuOne                                 */
    /* inputs: Number of strings, array of strings   */
    /* returned values: none                         */
    void MenuOne ( int numStrings, char **strArray )
    {
       int i, userInput = -41;
    
       printf("\nMenuOne function opened. %d\n", numStrings );
    
    
          for ( i = 0; i < numStrings; i++ )
          {
                printf("strArray[%2d] - %s\n", i, strArray[i] );
          }
    
          printf ("Please select which string you'd like to analyze, or 0 to quit.\n");
          scanf ("%d", &userInput );
          printf("%d is the user input\n", userInput);
    
          while( userInput < 0 ||  userInput > numStrings )
          {
             fprintf(stderr, "\nPlease enter a valid response. " );
             scanf("%d", &userInput );
          }
    
       MenuTwo ( userInput, strArray );
    }
    
    
    /* Controls the second level menu                    */
    /* Name: MenuTwo                                     */
    /* inputs: user integer selection, array of strings  */
    /* returned values: true/false ending condition      */
    int MenuTwo ( int input, char **strArray )
    {
       char select = 'Q';
       int end, numVowels, numCons, length, numWords, truefalse = 0;
    
       printf("\nMenuTwo just opened.\n");
    
       for ( end = 0; end < 19999; end++ )
       {
          printf("     \n   Analysis of the string :");
          printf("     \n   %s\n", strArray[input - 1] );
          printf("     \n   P - Is this string a palindrome ?");
          printf("     \n   V - How many vowels ?");
          printf("     \n   C - How many consonants ?");
          printf("     \n   L - What's its length ?");
          printf("     \n   W - How many words ?");
          printf("\n\n");
          printf("     \n   Q - Quit ");
          printf("\nEnter choice : ");
          scanf("%c", &select );
          
    if( select == 'Q' || select == 'q' )
          {
             end = 20000;
          }
          else if( select == 'P' || select == 'p' )
          {
             truefalse = IsPalindrome( input, strArray );
             if ( truefalse == 1 )
             {
                printf( "\nThe following string is a palindrome : %s\n", strArray[input-1]);
             }
             else
             {
                printf(" \nThe following string is not a palindrome : %s\n", strArray[input-1]);
             }
          }
          else if( select == 'V' || select == 'v' )
          {
             numVowels = NumVowels ( input, strArray );
             printf( "\nThere are %d vowels in : %s ", numVowels, strArray[input-1]);
          }
          else if( select == 'C' || select == 'c' )
    {
             numCons = NumCons ( input, strArray );
             printf( "\nThere are %d consonants in : %s ", numCons, strArray[input-1]);
          }
          else if( select == 'L' || select == 'l' )
          {
             length = strlen ( strArray[input-1] );
             printf("\n%d is the length of : %s", length, strArray[input-1] );
          }
          else if( select == 'W' || select == 'w' )
          {
             numWords = NumWords ( input, strArray );
             printf("\nThere's %d word(s) in : %s ", numWords, strArray[input-1] );
          }
    
       }
    
       return 1;
    }
    
    
    /* Tests to see if the string is a palindrome   */
    /* name: IsPalindrome                           */
    /* inputs: user input, array of strings         */
    /* returned values: true/false statement        */
    int IsPalindrome ( int input, char **strArray )
    {
       int output;
    
    
    
       return output;
    }
    
    
    /* Determines the number of vowels in the string   */
    /* name: NumVowels                                 */
    /* inputs: user input, array of strings            */
    /* returned values: number of vowels in string     */
    int NumVowels ( int input, char **strArray )
    {
       int numVowels;
    
    
    
       return numVowels;
    }
    
    
    /* Determines the number of consonants in the string   */
    /* name: NumCons                                       */
    /* inputs: user input, array of strings                */
    /* returned values: number of consonants in the string */
    int NumCons ( int input, char **strArray )
    {
       int numCons = 0;
       int i;
    
       if ( strArray[input-1][i] == 'n' )
       {
          numCons++;
       }
    
       return numCons;
    }
    
    
    /* Determines how many words are in the string     */
    /* name: NumWords                                  */
    /* inputs: user input, array of strings            */
    /* returned values: number of words in the string  */
    int NumWords ( int input, char **strArray )
    {
       int numWords;
    
    
    
       return numWords;
    }

  6. #6
    Registered User
    Join Date
    Apr 2004
    Posts
    38
    Here's my main file
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    #include "pal.h"
    
    int main( int argc, char* argv[] )
    {
       FILE *data;
       int numStrings;
       char** strArray;
    
       /* Ensures one data file is being entered at the command line  */
       if ( argc != 2 )
       {
          fprintf (stderr, "\nYou must enter the name of only one data file on the");
          fprintf (stderr, "\ncommand line to run this program." );
          fprintf (stderr, "\nExample: a.out filename\n");
          exit(-2);
       }
    
       data = fopen (argv[1],"r");
    
       /* Ensures the file is valid, and can be opened */
       if (data == NULL)
       {
          fprintf (stderr, "\nError opening %s\n", argv[1]);
          exit (-2);
       }
    
       PrintGreeting();
       PrintInstructions();
    
       numStrings = ReadNumStrings( data );
    
       FillArray ( data, strArray, numStrings );
    
       return 1;
    }
    And my header file:
    Code:
    /* Display greeting message */
    /* name: PrintGreeting      */
    /* inputs: none             */
    /* returned value: none     */
    void PrintGreeting() ;
    
    /* Display greeting message    */
    /* name: PrintInstructions     */
    /* inputs: none                */
    /* returned value: none        */
    void PrintInstructions() ;
    
    /* Reads in number of strings         */
    /* name: ReadNumStrings               */
    /* inputs: File pointer               */
    /* returned values: number of strings */
    int ReadNumStrings ( FILE *data ) ;
    
    /* Fills the array with the strings from the data file */
    /* name: FillArray                                     */
    /* inputs: Number of strings, file pointer             */
    /* returned values: none                               */
    void FillArray ( FILE *data, char **strArray, int numStrings ) ;
    
    /* Controls the first level menu                 */
    /* name: MenuOne                                 */
    /* inputs: Number of strings, array of strings   */
    /* returned values: none                         */
    void MenuOne ( int numStrings, char **strArray ) ;
    
    /* Controls the second level menu               */
    /* name: MenuTwo                                */
    /* inputs: integer input, array of strings      */
    /* returned values: true/false ending condition */
    int MenuTwo ( int input, char **strArray ) ;
    
    /* Tests to see if the string is a palindrome   */
    /* name: IsPalindrome                           */
    /* inputs: user input, array of strings         */
    /* returned values: true/false statement        */
    int IsPalindrome ( int input, char **strArray ) ;
    
    /* Determines the number of vowels in the string   */
    /* name: NumVowels                                 */
    /* inputs: user input, array of strings            */
    /* returned values: true/false statement           */
    int NumVowels ( int input, char **strArray ) ;
    
    /* Determines how many words are in the string     */
    /* name: NumWords                                  */
    /* inputs: user input, array of strings            */
    /* returned values: number of words in the string  */
    int NumWords ( int input, char **strArray ) ;
    
    /* Determines how many consonants are in the string     */
    /* name: NumCons                                        */
    /* inputs: user input, array of strings                 */
    /* returned values: number of words in the string       */
    int NumCons ( int input, char **strArray ) ;

  7. #7
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    Hrm. How about you try to duplicate the error in a (much) smaller amount of code.
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  8. #8
    Registered User
    Join Date
    Apr 2004
    Posts
    38
    I get the follow results when I run the program:
    Code:
    strArray[13] - A man, a plan, a cat, a canal: Panama?
    
    Please select which string you'd like to analyze, or 0 to quit.
    0
    Segmentation fault (core dumped)
    The code is in the MenuOne function:
    Code:
    printf ("Please select which string you'd like to analyze, or 0 to quit.\n");
    scanf ("%d", &userInput );
    printf("%d is the user input\n", userInput);

  9. #9
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    Your compiler should be warning something like:
    Code:
    Warning: Possible usage of strArray before initialization in function main
    That should be giving you a hint on the cause of the problem.

  10. #10
    Registered User
    Join Date
    Apr 2004
    Posts
    38
    So strArray has to be initialized in main?

    Edit: It compiles cleanly, no warnings/errors.

  11. #11
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    Try changing the end of your MenuOne function to this:
    Code:
    if( userInput) MenuTwo ( userInput, strArray );
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  12. #12
    Registered User
    Join Date
    Apr 2004
    Posts
    38
    Tried that. Didn't seem to have any effect.

  13. #13
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    Try putting a fflush( stdout ); at the end of the printf lines right after the sscanf, and see how far it gets before it dumps. It's possible it could be getting much farther without you knowing it.
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  14. #14
    Registered User
    Join Date
    Apr 2004
    Posts
    38
    I did that. I'm not familiar with fflush, so I don't know what to expect but I didn't see any change.

  15. #15
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    OK, to put it more simply: You must allocate memory for strArray before trying to store objects in it.

    Code:
       char ** strArray;
       /* At this point strArray points to a random memory address. Trying to dereference
          or write into random memory will lead to non-optimal results. Usually a crash. */
    
       ...
    
       numStrings = ReadNumStrings( data );
    
       /* Allocate memory for strArray before trying to use it */
       strArray = malloc(numStrings * sizeof(char *));
    
       if (strArray != NULL)
          FillArray ( data, strArray, numStrings );
    OR, on the stack:
    Code:
    char * strArray[MAX_NUMBER_OF_STRINGS];
    Just like you allocate memory for your character arrays before trying to store characters in them.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What am I doing worng? Segmentation fault, core dump
    By cookie in forum C Programming
    Replies: 4
    Last Post: 06-08-2007, 10:59 AM
  2. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 01:33 PM
  3. Core Dump / Segmentation Fault
    By Inquirer in forum Linux Programming
    Replies: 2
    Last Post: 04-08-2003, 09:24 PM
  4. odd segmentation fault occurence
    By gazsux in forum C Programming
    Replies: 6
    Last Post: 12-13-2002, 09:02 AM
  5. segmentation core dump - need help
    By knight101 in forum C++ Programming
    Replies: 1
    Last Post: 11-26-2001, 04:43 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21