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