Search code examples
cvalgrindfgets

valgrind error - printf from fgets


I am trying to read a line from a file and print it.

char *readLine(int n, FILE *file) {
    int i;
    int BUF=255;
    char temp[BUF];
    char puffer[BUF];
    for(i = 0; i < n-1; i++)
    if(fgets(temp, BUF, file) == NULL)
        return NULL; 

    if(fgets(puffer,BUF,file) == NULL)
        return NULL; 
    return puffer; 
}

I do not get errors if I do following:

char * temp=readLine(2,somefile);

but as soon as I

printf("%s",temp);

valgrind returns following error

Conditional jump or move depends on uninitialised value(s)
at 0x402EC04:strcrnul(in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
...

Solution

  • You are returning an array of characters that lives on the stack. When readLine finishes executing, the memory for puffer is automatically gone.

    You need to allocate memory on the heap. One quick fix is to do this:

    char *readLine(int n, FILE *file) {
    int i;
    int BUF=255;
    char temp[BUF];
    char puffer[BUF];
    char* returned_string;
    for(i = 0; i < n-1; i++)
        if(fgets(temp, BUF, file) == NULL)
            return NULL; 
    
    if(fgets(puffer,BUF,file) == NULL)
        return NULL; 
    
    returned_string = malloc (strlen (puffer) + 1);
    strcpy (returned_string, puffer);
    
    return returned_string; 
    }
    

    You don't really need two buffers in your function, though.