Thread: "Segmentation Fault: 11" error message

  1. #1
    Registered User
    Join Date
    Oct 2012
    Posts
    4

    "Segmentation Fault: 11" error message

    Hey everyone,

    I'm working on writing a program that reads in an ASCII image (an image made from clever placement of characters) from a file called image.txt and prints it to the screen. When compiling the code I receive no error messages, but when I attempt to run the program I receive a "segmentation fault: 11" message. If someone could explain what I'm doing wrong I would really appreciate it.

    I've attached the ASCII image I'm currently working with to this post. It's dimensions are 65 rows by 129 columns (given in the image). I want to make the maximum size image that this program can deal with 250x250. Thanks in advance!



    Code:
    #include <stdio.h>
    
    void printarray(char array[250][250], int rows, int cols);
    
    
    int main()
    {
        int rowlength, collength, i, j;
        char character;
        char array[rowlength][collength];
        FILE *ifp;
    
        ifp = fopen("image.txt", "r");
    
        if (ifp == NULL)
        {
            printf("Could not open numbers.txt\n");
        }
    
        else
        {
            printf("Opened file image.txt sucessfully\n");
            fscanf(ifp, "%d", &rowlength);
            fscanf(ifp, "%d", &collength);
    
            for (i = 0 ; i < rowlength ; i++)
            {
                for (j = 0 ; j < collength ; j++)
                {
                    fscanf(ifp, "%c", &character);
                    array[i][j] = character;
                }
                printf("\n");
            }
    
            printarray(array, rowlength, collength);
        }
    
        return 0;
    }
    
    
    void printarray(char array[250][250], int rows, int cols)
    {
        int i, j;
    
        printf("\n");
        for (i = 0 ; i < rows ; i++)
        {
            for (j = 0 ; j < cols ; j++)
            {
                printf("%c", array[i][j]);
            }
            printf("\n");
        }
        printf("\n");
    
    return;
    }
    Attached Files Attached Files

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    rowlength and collength are not initialized.

  3. #3
    Registered User
    Join Date
    Oct 2012
    Posts
    4
    rowlength and collength don't seem to be the problem. I replaced the variables with their actual values, 65 and 129, and the results were the same.

  4. #4
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Possible: Common newbie mistake
    Code:
    fscanf(ifp, "%c", &character);
    Is fixed by this; the space before the %c skips over whitespace like newlines.
    Code:
    fscanf(ifp, " %c", &character);
    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  5. #5
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Quote Originally Posted by avolkmar View Post
    rowlength and collength don't seem to be the problem. I replaced the variables with their actual values, 65 and 129, and the results were the same.
    Try using the max of 250 for both; you are still likely using space you do not own in calling printarray.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by avolkmar View Post
    rowlength and collength don't seem to be the problem. I replaced the variables with their actual values, 65 and 129, and the results were the same.
    They most definitely are the problem.

    The fundamental problem, I suspect, is that you somehow believe that variable length arrays are arrays that resize. They are not.

    To give a much simpler example, you are probably assuming this will work.
    Code:
    /*   Do not execute this code.   It exhibits undefined behaviour  */
    int main()
    {
         int dimension;
         char array[dimension];
         dimension = 10;
    
         array[dimension-1] = ' ';
    }
    This is a stripped down version of what your code is doing (your code also does it with multi-dimensional arrays, but that is a moot point).

    The reason this code is invalid is that dimension is initialised at the start. It's value istherefore indeterminate. Then the program execution reaches the statement.
    Code:
         char array[dimension];
    which attempts to retrieve the value of dimension (which is indeterminate) and create an array of that size. Technically, even the act of accessing the value of dimension causes undefined behaviour (i.e. it may nor may not cause the program to crash). But, if execution continues, we reach the next statement
    Code:
        dimension = 10;
    sets the value of dimension to 10. It does NOT affect array in any way. In particular, it does not resize array so it has 10 elements.

    Then the statement
    Code:
         array[dimension-1] = ' ';
    attempts to set the value of array[9] to be the space character. The thing is, the size of array is still not determined. So this will probably overwrite some area of memory that it shouldn't. Modern operating systems often terminate your program with prejudice at this point (unix sends a SIGSEGV signal to your program, which causes termination with a segmentation fault).
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  7. #7
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Quote Originally Posted by avolkmar View Post
    rowlength and collength don't seem to be the problem. I replaced the variables with their actual values, 65 and 129, and the results were the same.
    After solving the two things already mentioned (handling the newline at the end of each line and declaring your array after reading row and column from the file) you still have the problem that in your declaration of printarray()
    Code:
    void printarray(char array[250][250], int rows, int cols);
    the first parameter is translated by the compiler to "char (*array)[250]", i.e. "array" is a pointer to an array of 250 chars.

    In main() you have
    Code:
    int rowlength = 65;
    int collength = 129;
    char array[rowlength][collength];
    ...
    printarray(array, rowlength, collength);
    which means "array" is translated by the compiler to "char (*array)[129]". Thus you are calling printarray() with the wrong type for the first parameter.

    In printarray() you have
    Code:
    printf("%c", array[i][j]);
    "array" is basically a pointer to pointer to char. Thus "array[i]" points to the i-th row (which is itself an array of char).
    "array[i]" is the same as "*(array + i)", in other words to get to the beginning of the i-th row the compiler adds i * 250 bytes to the start of the array since the base type of "array" is char and the compiler expected an array with 250 elements. But you have provided an array with only 129 elements and that's why you are reading beyond valid memory after about half your image leading to the seg fault.

    The obvious solution to declare printarray() like
    Code:
    printarray(char array[rows][cols], int rows, int cols);
    doesn't work because the order of the parameter declarations is wrong. You need to write it like
    Code:
    printarray(int rows, int cols, char array[rows][cols]);
    Now "rows" and "cols" are declared before they get used in the array declaration. (Actually the first dimension is always ignored by the compiler and thus not needed.)

    If you don't understand some (or even all) of the above I suggest reading Ted Jensen's "Tutorial on pointers and arrays in C" and/or Section 6 of the C-FAQ ("Arrays and Pointers").
    Of course you can also ask further questions here.

    Bye, Andreas

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 04-10-2012, 02:31 PM
  2. How to debug "segmentation fault" in a parallel code?
    By smartfish in forum C Programming
    Replies: 2
    Last Post: 02-06-2012, 12:54 PM
  3. Segmentation fault when using fopen("filename","w+")
    By Marslakoo in forum C Programming
    Replies: 6
    Last Post: 11-21-2011, 08:15 AM
  4. Replies: 2
    Last Post: 10-31-2011, 11:57 AM
  5. [Segmentation Fault] fopen("filename","w")
    By gibbofresco in forum C Programming
    Replies: 7
    Last Post: 07-04-2009, 04:32 AM