Search code examples
cfgets

Strange fgets() problem


I'm trying to run this code on Windows 7 (64-bit, if it matters) after compiling it with GCC. If I declare bufsize as an int, the program freezes and Windows informs me that it's stopped working. If I use #define bufsize 123 it works fine, and it works fine if I replace bufsize with a number myself. What am I missing here?

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

    char* filename = argv[1];

    FILE* problem = fopen(filename, "r");
    if (!problem) {
        printf("File doesn't exist\n");
        exit(1);
    }

    char* line;
    while (fgets(line, bufsize, problem) != NULL) {        
        printf(line);
    }


    return 0;
}

Solution

  • line is a pointer, but it is pointing nowhere (or, better, it hasn't been initialized and its value is indeterminate and unusable). A pointer that points nowhere isn't terribly useful.

    Allocate some memory and make line point to that memory. Remember to deallocate memory when you no longer need it.

    line = malloc(200);
    if (line == NULL) { /* something went wrong, the pointer is pointing nowhere */ }
    /* ... use allocated memory ... */
    free(line);
    

    Oh ... and bufsize value should match the number of bytes you allocated.

    Also #include <stdlib.h> because malloc() and free() have their prototype there.