Read file contents of unknown size

I want to process the contents of a configuration file. The configuration file can be of any size. I get a bus error message after a program freezes when I run the following code:

FILE *fp;
struct stat st;
char *buffer;

fp = fopen(CONFIG_FILE, "r");
if (fp == NULL) {
    // error handling and cleanup omitted for brevity
}

fstat(fileno(fp), &st);
fread(buffer, sizeof(char), st.st_size, fp);
fprintf(stderr, "%s\n", *buffer);
fclose(fp);

I read that a bus error could be caused by a buffer overflow. I am sure I get buffer overflow with char *buffer. But then, how can I specify the size of the buffer at runtime?

EDIT . A bus error was caused by my laziness of hardcoding 1in passing. Sample code has been updated to fix this using sizeof(char).

+3
source share
3 answers

Use malloc(3). Placed:

buffer = malloc(st.st_size);

fread(). buffer, !

, *buffer printf(). , .

+6

malloc:

buffer = malloc(number_of_bytes_to_allocate);
if(buffer == NULL) {
    // error allocating memory
}

free, !

free(buffer);
+2

In C99 and provided that your configuration file should not be in the MiB range or a larger range, you can use VLA:

FILE *fp = fopen(CONFIG_FILE, "r");
if (fp == NULL) {
    // error handling and cleanup omitted for brevity
}

struct stat st;
fstat(fileno(fp), &st);  // Error check omitted
char buffer[st.st_size+1];
fread(buffer, sizeof(char), st.st_size, fp);
buffer[st.st_size] = '\0';
fprintf(stderr, "%s\n", *buffer);
fclose(fp);
+2
source

All Articles