tags:

views:

76

answers:

4

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;
}
+1  A: 

You have not allocated space for the buffer pointed to by line.

You should do:

line = malloc(bufsize);

and free it using:

free(line);
codaddict
+2  A: 

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.

pmg
`malloc(bufsize)`, then.
Jon Purdy
A: 
char* line = malloc(bufsize);
DigitalRoss
+1  A: 

bufsize is the size of the buffer that you are supposed to allocate and pass to fgets. You haven't allocated any buffer at all, and then you are lying to fgets telling it that you are passing a buffer of some specific size. It does not matter what size you are using or how you pass it to fgets - as long as you are not allocating any buffer, your code will crash or behave unpredictably.

As long as the buffer size is not very large, you can declare it as a local array, instead of allocating it dynamically

char line[bufsize];
while (fgets(line, bufsize, problem) != NULL) {        
    printf(line);
}
AndreyT
Just thought I'd mention this (the VLA) works for `C99`, which the OP is already using (mixed code and declarations).
pmg