...
This compliant solution solves the problem by expanding the buffer to read the entire contents from stdin instead of failing if the caller did not allocate enough space. If the allocation fails, it will return NULL, but otherwise, it returns a buffer of the received data, which the caller must free.
| Code Block |
|---|
|
#include <stdio.h>
void func(const char *file_name) {
FILE *fp = fopen(file_name, "wb+");
if (fp == NULL) {
/* Handle error */
}
} |
| Code Block |
|---|
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *get_filled_buffer(void) {
char temp[32];
char *ret = malloc(sizeof(temp));
char *end = ret;
if (!ret) {
return NULL;
}
while (fgets(temp, sizeof(temp), stdin)) {
size_t len = strlen(temp);
const size_t full_size = end - ret + len;
char *r_temp = realloc(ret, full_size + 1); /* NTBS */
if (r_temp) {
ret = r_temp;
strcat(ret, temp);
end = ret + full_size;
} else {
break;
}
if (feof(stdin) || temp[len] == '\n') {
return ret;
}
}
free(ret);
return NULL;
} |
...