title: How to use malloc() and memset()
body: <p>I am very new to C and trying to implement a <code>copy_buffer</code> function to allocate a new buffer, copy the contents from an existing buffer into the new buffer, and return the new buffer.</p>
  
  <p>I am trying to use <code>malloc()</code> and <code>memset()</code>, and I understand I need to <code>malloc</code> twice: one for the struct and one for the data. Do I need to <code>memset</code> twice too? Please point out where I wrote wrong for <code>copy_buffer</code> function.</p>
  
  <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  // Structure to hold a buffer of binary data
  // Note that we expect that it could hold null(0) characters,
  // so we can't rely on strlen to tell us the size or strcpy to copy the data
  typedef struct BufferStruct {
      char *data;
      int size;
  } Buffer;
  
  Buffer *copy_buffer(Buffer *buffer) {
      Buffer *new_buffer = (Buffer*)malloc(sizeof(Buffer));
      memset(new_buffer, 0, sizeof(Buffer));
      new_buffer-&gt;data = malloc(sizeof(char));
      memset(new_buffer-&gt;data, 0, sizeof(char));
      for (int i = 0; i &lt; buffer-&gt;size; ++i) {
          new_buffer-&gt;data[i] = buffer-&gt;data[i];
      }
      new_buffer-&gt;size = buffer-&gt;size;
      return new_buffer;
  }
  
  Buffer *example1() {
      Buffer *buffer = (Buffer*)malloc(sizeof(Buffer));
      buffer-&gt;data = "hello world\nthis is a string";
      buffer-&gt;size = strlen(buffer-&gt;data);
      return buffer;
  }
  
  // Example buffer storing 3 totally different strings in the same buffer (note the '\0')
  Buffer *example2() {
      Buffer *buffer = (Buffer*)malloc(sizeof(Buffer));
      buffer-&gt;data = "this string has null\0characters\0 in the middle, beware!";
      buffer-&gt;size = 55;
      return buffer;
  }
  
  //
  // Use fopen to create a file for writing
  // Then fwrite to write the buffer to a file
  //
  void write_buffer(const char *filename, Buffer *buffer) {
      FILE *file = fopen(filename, "w");
      fwrite(buffer-&gt;data, 1, buffer-&gt;size, file);
      fclose(file);
  }
  
  int main() {
      Buffer *example = example2();
      Buffer *copied = copy_buffer(example);
  
      write_buffer("example1.bin", copied);
      return 0;
  }
  </code></pre>