Correctly free resources in uiLoadGame

This commit is contained in:
Simon Gellis 2024-11-02 13:25:37 -04:00
parent 00066f225b
commit 007a89d8b8
1 changed files with 17 additions and 8 deletions

25
ui.c
View File

@ -46,9 +46,10 @@ void uiDestroy(UIContext *ui) {
int uiLoadGame(UIContext *ui, const char *path) { int uiLoadGame(UIContext *ui, const char *path) {
FILE *file = fopen(path, "rb"); FILE *file = fopen(path, "rb");
uint8_t *rom; uint8_t *rom = NULL;
long fileSize; long fileSize;
uint32_t romSize; uint32_t romSize;
int result;
if (!file) { if (!file) {
perror("could not open file"); perror("could not open file");
@ -57,36 +58,44 @@ int uiLoadGame(UIContext *ui, const char *path) {
if (fseek(file, 0, SEEK_END)) { if (fseek(file, 0, SEEK_END)) {
perror("could not seek file end"); perror("could not seek file end");
return -1; goto close_file;
} }
fileSize = ftell(file); fileSize = ftell(file);
if (fileSize == -1) { if (fileSize == -1) {
perror("could not read file size"); perror("could not read file size");
return -1; goto close_file;
} }
if (fseek(file, 0, SEEK_SET)) { if (fseek(file, 0, SEEK_SET)) {
perror("could not seek file start"); perror("could not seek file start");
return -1; goto close_file;
} }
romSize = (uint32_t) fileSize; romSize = (uint32_t) fileSize;
rom = malloc(romSize); rom = malloc(romSize);
if (!rom) { if (!rom) {
perror("could not allocate ROM"); perror("could not allocate ROM");
return -1; goto close_file;
} }
fread(rom, 1, romSize, file); fread(rom, 1, romSize, file);
if (ferror(file)) { if (ferror(file)) {
perror("could not read file"); perror("could not read file");
return -1; goto free_rom;
} }
if (fclose(file)) { result = fclose(file);
file = NULL;
if (result) {
perror("could not close file"); perror("could not close file");
return -1; goto free_rom;
} }
emuLoadGame(&ui->emu, rom, romSize); emuLoadGame(&ui->emu, rom, romSize);
return 0; return 0;
free_rom:
free(rom);
close_file:
if (file) fclose(file);
return -1;
} }
static const char *MENU_ITEMS[4] = { static const char *MENU_ITEMS[4] = {