title: Memory allocation error - in Linux but not OSX Unix
body: <p>I'm writing some code for a statistics package, and I start off by reading in data to a pointer array. I initialize the pointer and allocate sufficient memory using malloc; however, I sometimes get an error in the memory allocation at the end of the code below. </p>
  
  <pre><code>#include &lt;stddef.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include "stats.h"
  
  int main(int argc, char **argv) {
  FILE *fp, *outFile, *outBin;    // create a file identifier
  size_t n, nbins; // # of data points
  double *data; // pointer to hold data
  double average, variance, *med; // stat returns
  int medianComplete, histComplete, i; // return 1 on success
  hist_t *Histogram;
  
  // read in the number of bins from exe arguments
  nbins = atoi(argv[1]);
  nbins = (size_t)nbins;
  
  // open the binary datafile and read in first value
  // which is number of data points
  // use exe input for filename
  fp = fopen(argv[2],"rb");
  fread(&amp;n, sizeof(size_t),1,fp);
  
  // allocate enough memory to hold all data
  data = (double*)malloc(sizeof(double)*n);
  if (!data)
      printf("Memory allocation error");
  fread(data,sizeof(double),n,fp);
  </code></pre>
  
  <p>This program compiles and runs well on my personal machine (MacOSX), but fails due to a segmentation error when I try to run it on a Linux server. I used Valgrind to see if I could track down the error and I receive the following result.</p>
  
  <pre><code>==8641== Warning: silly arg (-501426814648844128) to malloc()
  ==8641== Invalid write of size 1
  ==8641==    at 0x4C2B20D: mempcpy (mc_replace_strmem.c:956)
  ==8641==    by 0x4EA2F15: _IO_file_xsgetn (fileops.c:1423)
  ==8641==    by 0x4E971D2: fread (iofread.c:44)
  ==8641==    by 0x40086D: main (runstats.c:28)
  ==8641==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
  </code></pre>
  
  <p>This is the first program I've ever written that uses pointers, and I'm at a loss for why it would work on one system but not the other.</p>