From e2cd2d71f7db8816b074c1561b72970d0c9e493d Mon Sep 17 00:00:00 2001 From: Henry Amrhein Date: Wed, 2 Jan 2013 12:58:36 -0800 Subject: [PATCH] bam_cat.c: check return value of malloc() in bam_cat() wrapped fwrite() calls with error-checking --- bam_cat.c | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/bam_cat.c b/bam_cat.c index 0fde045..43df917 100644 --- a/bam_cat.c +++ b/bam_cat.c @@ -86,7 +86,10 @@ int bam_cat(int nfn, char * const *fn, const bam_header_t *h, const char* outbam } if (h) bam_header_write(fp, h); - buf = (uint8_t*) malloc(BUF_SIZE); + if ((buf = (uint8_t*) malloc(BUF_SIZE)) == NULL) { + fprintf(stderr, "[%s] failed to allocate input buffer.\n", __func__); + return -1; + } for(i = 0; i < nfn; ++i){ BGZF *in; bam_header_t *old; @@ -121,14 +124,26 @@ int bam_cat(int nfn, char * const *fn, const bam_header_t *h, const char* outbam fprintf(stderr, "[%s] ERROR: truncated file?: '%s'.\n", __func__, fn[i]); return -1; } - fwrite(ebuf, 1, len, fp_file); + if (fwrite(ebuf, 1, len, fp_file) < len) { + fprintf(stderr, "[%s] failed to write to output file.\n", __func__); + return -1; + } memcpy(ebuf,ebuf+len,diff); memcpy(ebuf+diff,buf,len); - } else { - if(j!=0) fwrite(ebuf, 1, es, fp_file); + } + else { + if(j!=0) { + if (fwrite(ebuf, 1, es, fp_file) < es) { + fprintf(stderr, "[%s] failed to write to output file.\n", __func__); + return -1; + } + } len-= es; memcpy(ebuf,buf+len,es); - fwrite(buf, 1, len, fp_file); + if (fwrite(buf, 1, len, fp_file) < len) { + fprintf(stderr, "[%s] failed to write to output file.\n", __func__); + return -1; + } } j=1; } @@ -141,7 +156,9 @@ int bam_cat(int nfn, char * const *fn, const bam_header_t *h, const char* outbam if(((gzip1!=GZIPID1) || (gzip2!=GZIPID2)) || (isize!=0)) { fprintf(stderr, "[%s] WARNING: Unexpected block structure in file '%s'.", __func__, fn[i]); fprintf(stderr, " Possible output corruption.\n"); - fwrite(ebuf, 1, es, fp_file); + if (fwrite(ebuf, 1, es, fp_file) < es) { + fprintf(stderr, " Also, failed to write final block.\n"); + } } } bam_header_destroy(old); -- 2.30.2