Advertisement
Guest User

Untitled

a guest
Jan 19th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.81 KB | None | 0 0
  1. #include "linalg.h"
  2. typedef struct matrix
  3. {
  4.     size_t mrows;
  5.     size_t ncols;
  6.     double *arr;
  7. } matrix;
  8. void MatDestruct(Mat mat)
  9. {
  10.     if(mat==NULL) // Matrix doesn't have memory allocated to it.
  11.     {
  12.         fprintf(stderr,"Error: mat points to NULL in MatDestruct.\n");
  13.         exit(EXIT_FAILURE);
  14.     }
  15.     double compare=(mat->mrows)*(mat->ncols);
  16.     if(compare>ULONG_MAX) // Matrix dimensions are too large.
  17.     {
  18.         fprintf(stderr,"Error: input dimensions out of range in MatDestruct.\n");
  19.         exit(EXIT_FAILURE);
  20.     }
  21.     if(mat->arr!=NULL) // Safeguard against using this function on already initialized matrices.
  22.     {
  23.         for(size_t i=0;i<(mat->mrows)*(mat->ncols);i++) // Zeroes the data before freeing the memory.
  24.         {
  25.             mat->arr[i]=0;
  26.         }
  27.         free(mat->arr);
  28.     }
  29.     mat->mrows=0;
  30.     mat->ncols=0;
  31.     mat->arr=NULL;
  32.     free(mat);
  33.     mat=NULL;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement