From 11b891a5046e9970ab2827baeeff3a0128dfdb69 Mon Sep 17 00:00:00 2001 From: JJM-Student Date: Thu, 9 Feb 2017 02:05:42 -0600 Subject: [PATCH] Update hw3.c Converted allocate memory from a void to int so that it can return a failure state value. Also eliminated exit commands within allocate function. Updated end of main leveraging changes to allocate function so that steps after allocate are skipped if allocation fails. --- hw3.c | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/hw3.c b/hw3.c index 8f0eab6..5cf7d16 100644 --- a/hw3.c +++ b/hw3.c @@ -1,19 +1,26 @@ #include #include -void allocate_memory(double ** buf, long N) +int allocate_memory(double ** buf, long N) /* Returns a 0 on success, 1 on failed */ { if (N>1000000) { printf("Tried to hog up too much memory!\n"); - exit(0); } - * buf=(double *)malloc(N*sizeof(double)); + else + { + * buf=(double *)malloc(N*sizeof(double)); if (*buf==NULL) { printf("Allocation failed\n"); - exit(0); } + else + { + return 0; /* Only returned for N<=1000000 and *buf != NULL */ + } + return 1; /* Defaults to returning a failed 1 for N>1000000 or Allocation failed - could later distinguish these! */ + } + } void gen_random_numbers(double *buf,long N) { @@ -41,10 +48,12 @@ int main(int argc, char *argv[]) exit(0); } N=atoi(argv[1]); - allocate_memory(&buffer, N); + if (allocate_memory(&buffer, N) == 0) /* Updated code here so that following steps only run on successful allocation */ + { gen_random_numbers(buffer,N); average=compute_average(buffer,N); printf("The average we have been waiting on is %f\n",average); + } return(0); }