diff --git a/src/read_file.c b/src/read_file.c index cf6c3f5..62f0d81 100644 --- a/src/read_file.c +++ b/src/read_file.c @@ -1,10 +1,11 @@ -#include -#include -#include -#include -#include -#include -#include "ucore/read_file.h" +#include +#include +#include +#include +#include +#include +#include +#include "ucore/read_file.h" #define CHUNK_SZ 1024 @@ -27,17 +28,21 @@ uc_read_file(const char *f, size_t *length, size_t max) } if ((statb.st_mode & S_IFMT) == S_IFREG) { - if ((size_t)statb.st_size > max) { + if (statb.st_size > (off_t)max) { errno = EMSGSIZE; goto out_close; } - alloc_sz = (size_t) statb.st_size + 1; // + 1 to avoid one realloc - s = malloc((size_t) alloc_sz + 1); //+1 for nul terminator + if (statb.st_size > SSIZE_MAX) { + //otherwise we cannot detect the return value of read() + alloc_sz = SSIZE_MAX; + } else { + alloc_sz = statb.st_size; + } } else { alloc_sz = CHUNK_SZ; - s = malloc(alloc_sz + 1); //+1 for nul terminator } + s = malloc(alloc_sz + 1); //+1 for nul terminator if (s == NULL) { goto out_close; }