title: Pointer passed to function which allocates memory to it only works if pointer NULL intialized
body: <p>I was writing a function to read a file into memory and encountered a strange problem. The returned pointer could only be free()'ed successfully if it was intialized to NULL before passing it to the function. This is the code,</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;sys/stat.h&gt;
  
  
  ssize_t
  file_size(const char *path)
  {
      struct stat stats;
  
      if (stat(path, &amp;stats))
          return (-1);
  
      return (stats.st_size);
  }
  
  ssize_t
  read_file(const char *path, char *data)
  {
      data = NULL;
  
      FILE *fp;
  
      ssize_t tmp;
      size_t fl;
  
      tmp = file_size(path);
      if (tmp &lt; 0) goto err;
      fl = (size_t)tmp;
  
      data = malloc(fl);
      if (data == NULL) goto err;
      
      fp = fopen(path, &quot;rb&quot;);
      if (fp == NULL) goto err;
  
      if (fread(data, 1L, fl, fp) != fl) goto err;
  
      if (ferror(fp)) goto err;
  
      fclose(fp);
  
      return (fl);
      
  err:
      if (fp)
      {
          int errno_save = errno;
          fclose(fp);
          errno = errno_save;
      }
  
      free(data);
  
      return (-1);
  }
  
  int
  main(void)
  {
      char *fdata; // If this is initialized to NULL, then the program works fine
      size_t fdata_len;
      
      fdata_len = read_file(&quot;/home/varad/wallpaper.jpg&quot;, fdata);
  
      printf(&quot;read %zu bytes.\n&quot;, fdata_len);
  
      free(fdata); // Segfault happens over here
  
      return (0);
  }
  
  </code></pre>
  <p>If the variable 'fdata' in the main function is not initialized to NULL, the program fails with the following output:</p>
  <pre><code>read 2599298 bytes.
  Segmentation fault (core dumped)
  </code></pre>
  <p>However, if it is initialize to NULL, then it apparently runs as expected with the following output:</p>
  <pre><code>read 2599298 bytes.
  </code></pre>
  <p>I have tried to debug this program with gdb, and the segmentation fault happens at the free() call at the end of the main function. Any help will be appreciated.</p>
  <p>Thanks in advance,
  Varad</p>