Question

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.

Was it helpful?

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.

OTHER TIPS

Maybe you just left something out of your snippet, but you didn't show the structure being allocated.

line *lineRead; // uninitialized pointer: access to any field crashes
lineRead = (line*) malloc( sizeof( line_description ) );

Or, if you don't need it to be on the heap (especially considering that a stack object in outermost scope in main has lifetime of the entire program anyway),

line lineRead; // don't need to use a pointer!

You declare lineRead to be a pointer to a line, but you don't actually set it to point to anything. When you then try to access the random location that the uninitialized pointer happens to point to, you get a segmentation fault.

If you only need lineRead in the local scope it shouldn't be a pointer, just declare it as

line lineRead;

If lineRead needs to live longer that the function and so really needs to be dynamically allocated, use a pointer but also reserve memory for the struct it should be pointing to:

line *lineRead = malloc(sizeof(line));
lineRead->buffer[0] = '\0'; // or any other initializations...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top