mirror of
https://github.com/sparkle-project/Sparkle
synced 2026-11-27 05:04:27 +00:00
Improve error handling on readfile()
This commit is contained in:
1 parent
71330366d8
commit
159c16fc12
1 file changed
+19
-15
Vendored
+19
-15
@@ -10,20 +10,21 @@
|
||||
|
||||
u_char *readfile(const char *filename, off_t *outSize)
|
||||
{
|
||||
int success = -1;
|
||||
u_char *buffer = NULL;
|
||||
|
||||
FILE *file = fopen(filename, "r");
|
||||
if (file == NULL) {
|
||||
return NULL;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
if (fseek(file, 0L, SEEK_END) != 0) {
|
||||
fclose(file);
|
||||
return NULL;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
long offset = ftell(file);
|
||||
if (offset == -1) {
|
||||
fclose(file);
|
||||
return NULL;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
size_t size = (size_t)offset;
|
||||
@@ -34,25 +35,28 @@ u_char *readfile(const char *filename, off_t *outSize)
|
||||
|
||||
/* Allocate size + 1 bytes instead of newsize bytes to ensure
|
||||
that we never try to malloc(0) and get a NULL pointer */
|
||||
u_char *buffer = malloc(size + 1);
|
||||
buffer = malloc(size + 1);
|
||||
if (buffer == NULL) {
|
||||
fclose(file);
|
||||
return NULL;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
if (fseek(file, 0L, SEEK_SET) != 0) {
|
||||
fclose(file);
|
||||
free(buffer);
|
||||
return NULL;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
if (fread(buffer, 1, size, file) < size) {
|
||||
fclose(file);
|
||||
free(buffer);
|
||||
return NULL;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
fclose(file);
|
||||
success = 0;
|
||||
cleanup:
|
||||
if (success == -1) {
|
||||
free(buffer);
|
||||
buffer = NULL;
|
||||
}
|
||||
if (file != NULL) {
|
||||
fclose(file);
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
Reference in new issue
Block a user