From 1de611b31a18b40e357fbd27f987f76162d1a05e Mon Sep 17 00:00:00 2001 From: Eduard Drusa Date: Tue, 28 Jan 2025 23:59:12 +0100 Subject: [PATCH] Fix: Segmentation fault on file open error Add basic error handling for input/output file open action. Quit with error message instead of crashing trying to write unopened file handle. --- hex2dfu.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/hex2dfu.c b/hex2dfu.c index 0c45d4b..9a91fed 100644 --- a/hex2dfu.c +++ b/hex2dfu.c @@ -28,7 +28,7 @@ int main (int argc, char **argv) { int targen_number = 0; int i, c, vid =0x0483, pid = 0xdf11, ver = 0xffff; char *tar0 = NULL, *tar0_lab = NULL, *out_fn = NULL; - FILE *inFile, *outFile; + FILE *inFile = NULL, *outFile = NULL; unsigned char json_output = 0; unsigned int max_address = 0x08200000; @@ -149,6 +149,10 @@ int main (int argc, char **argv) { #endif inFile = fopen ( tar0, "r"); + if (!inFile) { + perror("error: open input file"); + return 1; + } tar0_buf = ihex2bin_buf(&tar0_start_address, &tar0_len, inFile, max_address); tar0_len = tar0_len + ((tar0_len & 0x07) ? (8 - (tar0_len & 0x07)) : 0); fclose (inFile); @@ -253,6 +257,11 @@ int main (int argc, char **argv) { //write DFU to file outFile = fopen (out_fn, "wb"); + if (!outFile) { + perror("error: open output file"); + return 1; + } + c = fwrite (dfu, dfu_len, 1, outFile); fclose(outFile); if (c != 1) {