Search code examples
carraysstructsegmentation-faultfgets

Writing to a character array that is a member of a struct


this is my first time posting a question here - I've searched for ones that are similar, but none came up that I found.

Here is the snippet from my header:

#define LINE_LEN_MAX 256

typedef struct line_description {
    char buffer[LINE_LEN_MAX + 1];
    [...]
} line;

And here is the snippet from my main function:

int main(int argc, char *argv[]) {

    line *lineRead;

    //input: valid FILE *, read from cmdline
    //char buffer[LINE_LEN_MAX + 1];

    while(fgets(lineRead->buffer, LINE_LEN_MAX + 1, input) != NULL) {

        [...]

        memset(lineRead->buffer, 0, LINE_LEN_MAX + 1);
    }
}

I keep getting a segfault. If I comment out the 'memset()' line I can read exactly 3 lines from my input file before getting a segfault.

However, if I replace 'lineRead->buffer' with a local char[] I am able to read my input file perfectly.

What am I not understanding about structs here? What I think I want is a pointer to the beginning of the char[] inside the struct, but obviously this is not what is happening.

EDIT: Sorry, forgot to specify: I am not using dynamic memory here.


Solution

  • lineRead in your program is an uninitialized pointer, which is probably not what you wanted.

    You should allocate some storage space for a line by writing e.g. line lineRead instead, which will allocate a line struct on the stack. Then use . rather than -> to access its members.