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* filena开发者_JS百科me = 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;
}
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.
You have not allocated space for the buffer pointed to by line
.
You should do:
line = malloc(bufsize);
and free it using:
free(line);
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);
}
char* line = malloc(bufsize);
精彩评论