Thread: Segmentation fault

  1. #1
    Registered User
    Join Date
    Dec 2020
    Posts
    6

    Segmentation fault

    I am pretty new to programming and I am getting a segmentation fault and I have no idea where this is happening.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #define FIELDWIDTH 3 //The width of the hopscotch field.
    
    
    FILE *in;   //Pointer to files
    FILE *out;
    
    
    int max_score(int *tally_row, int middle_index);
    int** alloc_no_of_marbles(int field_length, int fieldWidth);
    int** alloc_score_of_each_square(int field_length, int fieldWidth);
    
    
    int main(void)
    {
        char inFileName[] = "hopscotch.dat";   //Open files for reading
        char outFileName[] = "hopscotch.out";
    
    
        int field_length, i, j;
    
    
        fscanf(in, "%d", &field_length);
    
    
        int **no_of_marbles = alloc_no_of_marbles(field_length, FIELDWIDTH);
        int **score_of_each_square = alloc_score_of_each_square(field_length, FIELDWIDTH);
    
    
        for(i=0; i<field_length; i++)
        {
            for(j=0; j<FIELDWIDTH; j++)
            {
                fscanf(in, "%d", &no_of_marbles[i][j]);
            }
        }
    
    
        for(i=0; i<field_length; i++)
        {
            for(j=0; j<FIELDWIDTH; j++)
            {
                score_of_each_square[i][j] =
                ( ((i-1) < 0) ? 0 : score_of_each_square[i-1][max_score(score_of_each_square[i-1],j)] )
                + no_of_marbles[i][j];
            }
        }
    
    
        int path_score = score_of_each_square[field_length-1][max_score(score_of_each_square[field_length-1],1)];
        char hop_path[field_length+1];
        int current_row = field_length, current_pos = 1, previous_pos;
    
    
        for(i=current_row; i>=0; i--)
        {
            if(i==0) previous_pos = 1;
            else previous_pos = max_score(score_of_each_square[i-1], current_pos);
            switch(current_pos - previous_pos){
                case -1: hop_path[i] = 'L';
                break;
                case 0: hop_path[i] = 'D';
                break;
                case 1: hop_path[i] = 'R';
                break;
            }
        current_pos = previous_pos;
        }
    
    
        fprintf(out, "Maximum possible score: %d\n", path_score);
        fprintf(out, "A path that achieves this score: ");
        for(i=0; i<=field_length; i++)
        fprintf(out, "%c", hop_path[i]);
        fprintf(out, "\n");
        return 0;
    }
    
    
    int max_score(int* tally_row, int middle_index){ 
        int k, value = 0, max_value_index = -1;
        for(k=middle_index-1; k<=middle_index+1; k++)
        {
            if(k >= 0 && k < FIELDWIDTH)
                if(tally_row[k] > value)
                {
                    value = tally_row[k];
                    max_value_index = k;
                }
        }
        return max_value_index;
    } 
    
    
    int **alloc_no_of_marbles(int field_length, int fieldWidth)
    {
        int **hopArr;
        int *aux1;
        int i, j;
        aux1 = (int *) malloc(field_length*fieldWidth*sizeof(int));
        if (aux1 == NULL) exit(1);
        hopArr = (int **) malloc(field_length*sizeof(int *));
        if(hopArr == NULL) exit(1);
        for(i=j=0; i<field_length; i++, j+=fieldWidth)
        hopArr[i] = &aux1[j];
        return hopArr;
    } 
    
    
    int **alloc_score_of_each_square(int field_length, int fieldWidth)
    {
        int **talArr;
        int *aux2;
        int i, j;
        aux2 = (int *) malloc(field_length*fieldWidth*sizeof(int));
        if (aux2 == NULL) exit(1);
        talArr = (int **) malloc(field_length*sizeof(int *));
        if(talArr == NULL) exit(1);
        for(i=j=0; i<field_length; i++, j+=fieldWidth)
        talArr[i] = &aux2[j];
        return talArr;
    }

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,739
    Ok, first of all, you need to learn how to use the debugger. It's an essential skill for all programmers.
    A Quickstart Guide to Debugging C Programs with gdb

    If you're using an IDE, it may be as simple as clicking a special button that runs it in debug mode.
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Dec 2020
    Posts
    6
    I was using online c compiler. it does not have any debugging tool. Sorry

  4. #4
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    What are the rules of your game? Give some input and expected output.
    A little inaccuracy saves tons of explanation. - H.H. Munro

  5. #5

  6. #6
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    Problem description: https://ece15.ucsd.edu/Exams/Problem3/problem3.pdf

    What about some input that produces a segfault?
    A little inaccuracy saves tons of explanation. - H.H. Munro

  7. #7
    Registered User
    Join Date
    Dec 2020
    Posts
    6
    I am sorry, I did not get what you just meant.

  8. #8
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    You say you are getting a segmentation fault.
    The example input you linked to doesn't produce a fault for me with your code.
    What input gives you the fault?

    This is the code I'm running. I simplified your code a little and made it easier for me to read by using shorter names.
    It should act the same as your code, though.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    #define WIDTH 3  // The width of the hopscotch field
     
    int max_score(int *row, int index);
    int **alloc_grid(int length, int width);
     
    int main()
    {
        //const char *inFileName = "hopscotch.dat";
        //const char *outFileName = "hopscotch.out";
        FILE *in = stdin;
        FILE *out = stdout;
     
        int length;
        fscanf(in, "%d", &length);
     
        int **marbles = alloc_grid(length, WIDTH);
        int **scores  = alloc_grid(length, WIDTH);
     
        for (int i = 0; i < length; i++)
            for (int j = 0; j < WIDTH; j++)
                fscanf(in, "%d", &marbles[i][j]);
     
        for (int i = 0; i < length; i++)
            for (int j = 0; j < WIDTH; j++)
                scores[i][j] = (i == 0 ? 0 : scores[i - 1][max_score(scores[i - 1], j)])
                             + marbles[i][j];
     
        int path_score = scores[length - 1][max_score(scores[length - 1], 1)];
        char path[length + 1];
     
        for (int i = length, pos = 1; i >= 0; i--)
        {
            int prev = (i == 0 ? 1 : max_score(scores[i - 1], pos));
            switch (pos - prev)
            {
            case -1: path[i] = 'L'; break;
            case  0: path[i] = 'D'; break;
            case  1: path[i] = 'R'; break;
            }
            pos = prev;
        }
     
        fprintf(out, "Maximum possible score: %d\n", path_score);
        fprintf(out, "A path that achieves this score: ");
        for (int i = 0; i <= length; i++)
            fprintf(out, "%c", path[i]);
        fprintf(out, "\n");
     
        free(marbles[0]);
        free(marbles);
        free(scores[0]);
        free(scores); 
     
        return 0;
    }
     
    int max_score(int *row, int index)
    {
        int imax = index;
        if (index > 0         && row[index - 1] > row[imax]) imax = index - 1;
        if (index < WIDTH - 1 && row[index + 1] > row[imax]) imax = index + 1;
        return imax;
    }
     
    int **alloc_grid(int length, int width)
    {
        int  *aux  = malloc(length * width * sizeof *aux );    if (!aux)  exit(1);
        int **grid = malloc(length         * sizeof *grid);    if (!grid) exit(1);
        for (int i = 0; i < length; i++) grid[i] = &aux[i * width];
        return grid;
    }
    Last edited by john.c; 12-19-2020 at 09:58 AM.
    A little inaccuracy saves tons of explanation. - H.H. Munro

  9. #9
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,106
    You have to open the file for reading before you can process the file!

    Where is your call to fopen()?

  10. #10
    Registered User
    Join Date
    Dec 2020
    Posts
    6
    Quote Originally Posted by john.c View Post
    You say you are getting a segmentation fault.
    The example input you linked to doesn't produce a fault for me with your code.
    What input gives you the fault?

    This is the code I'm running. I simplified your code a little and made it easier for me to read by using shorter names.
    It should act the same as your code, though.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    #define WIDTH 3  // The width of the hopscotch field
     
    int max_score(int *row, int index);
    int **alloc_grid(int length, int width);
     
    int main()
    {
        //const char *inFileName = "hopscotch.dat";
        //const char *outFileName = "hopscotch.out";
        FILE *in = stdin;
        FILE *out = stdout;
     
        int length;
        fscanf(in, "%d", &length);
     
        int **marbles = alloc_grid(length, WIDTH);
        int **scores  = alloc_grid(length, WIDTH);
     
        for (int i = 0; i < length; i++)
            for (int j = 0; j < WIDTH; j++)
                fscanf(in, "%d", &marbles[i][j]);
     
        for (int i = 0; i < length; i++)
            for (int j = 0; j < WIDTH; j++)
                scores[i][j] = (i == 0 ? 0 : scores[i - 1][max_score(scores[i - 1], j)])
                             + marbles[i][j];
     
        int path_score = scores[length - 1][max_score(scores[length - 1], 1)];
        char path[length + 1];
     
        for (int i = length, pos = 1; i >= 0; i--)
        {
            int prev = (i == 0 ? 1 : max_score(scores[i - 1], pos));
            switch (pos - prev)
            {
            case -1: path[i] = 'L'; break;
            case  0: path[i] = 'D'; break;
            case  1: path[i] = 'R'; break;
            }
            pos = prev;
        }
     
        fprintf(out, "Maximum possible score: %d\n", path_score);
        fprintf(out, "A path that achieves this score: ");
        for (int i = 0; i <= length; i++)
            fprintf(out, "%c", path[i]);
        fprintf(out, "\n");
     
        free(marbles[0]);
        free(marbles);
        free(scores[0]);
        free(scores); 
     
        return 0;
    }
     
    int max_score(int *row, int index)
    {
        int imax = index;
        if (index > 0         && row[index - 1] > row[imax]) imax = index - 1;
        if (index < WIDTH - 1 && row[index + 1] > row[imax]) imax = index + 1;
        return imax;
    }
     
    int **alloc_grid(int length, int width)
    {
        int  *aux  = malloc(length * width * sizeof *aux );    if (!aux)  exit(1);
        int **grid = malloc(length         * sizeof *grid);    if (!grid) exit(1);
        for (int i = 0; i < length; i++) grid[i] = &aux[i * width];
        return grid;
    }
    Could you please explain to me why we are not using the commands fopen and fclose since we have to read it from a file and output to a file. Since I am learning I want to be as clear as possible.

  11. #11
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    I'm setting in to stdin and out to stdout just for testing, so I'm reading and writing to the console.
    Anyway, I assumed you weren't actually running the code as given, but if you are not opening the files anywhere then that's a problem.
    Last edited by john.c; 12-19-2020 at 10:27 AM.
    A little inaccuracy saves tons of explanation. - H.H. Munro

  12. #12
    Registered User
    Join Date
    Dec 2020
    Posts
    6
    Quote Originally Posted by john.c View Post
    I'm setting in to stdin and out to stdout just for testing, so I'm reading and writing to the console.
    Anyway, I assumed you weren't actually running the code as given, but if you are not opening the files anywhere then that's a problem.
    So, if I wanted it to take input from somewhere and write on another file what would I have done differently?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In GDB no segmentation fault but while running segmentation fault
    By Tamim Ad Dari in forum C++ Programming
    Replies: 2
    Last Post: 12-10-2013, 11:16 AM
  2. Segmentation fault
    By DeanWinchester in forum C Programming
    Replies: 3
    Last Post: 05-30-2012, 01:27 PM
  3. segmentation fault
    By killero in forum C Programming
    Replies: 2
    Last Post: 05-30-2012, 08:25 AM
  4. Segmentation fault
    By Kemaratu in forum C Programming
    Replies: 6
    Last Post: 11-30-2009, 03:40 AM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 11:09 PM

Tags for this Thread