Search code examples
csegmentation-faultgetlinememcpy

Bizarre segfault on memcpy in getline


Consider this bit of stripped-down code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main()
{
   FILE * infile;
   char * buffer; // = malloc(sizeof(char));                                 
   ssize_t line_length;
   size_t nbytes;
   int x1;
   int x2;
   //int x3;                                                                 

   infile = fopen("file.txt", "r");
   getline(&buffer, &nbytes, infile);
}

As shown, the code runs with no error.

If I uncomment int x3, I get a segfault on the getline line. I have shown you the entire program here -- x3 is never used, and I have no idea how this declaration could matter.

I suspect that this is a memory allocation issue, because uncommenting the = malloc part removes the segfault. But what could cause this interaction between x3 and getline?


Solution

  • The problem is that both buffer and nbytes are unitialized. From man getline():

    Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc(3)-allocated buffer *n bytes in size. If the buffer is not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary.

    getline() will be writing to a random location memory (whatever value buffer holds) that it has been told is nbytes (some unknown value) in size. This is undefined behaviour.

    To correct, initialize the variables to valid values and check the result of fopen() before using.