title: Copy a string to a malloc'd array of strings
body: <p>I thought I understood the answer to <a href="https://stackoverflow.com/questions/5935933/dynamically-create-an-array-of-strings-with-malloc">this question</a> but I don't.  I understand the first result but I still don't know how to do the copy correctly.  I tried the following code:</p>
  
  <pre><code>// TstStrArr.cpp : Defines the entry point for the console application.
  //
  
  #include "stdafx.h"
  
  #include &lt;string.h&gt;
  #include &lt;malloc.h&gt;
  
  
  int main()
  {
      char ** StrPtrArr;
      char    InpBuf0[] = "TstFld0";
      char    InpBuf1[] = "TstFld1";
  
      StrPtrArr = (char **)malloc(2 * sizeof(char *));
  
      StrPtrArr[0] = (char *)malloc(10 + 1);
      printf("inpbuf=%s   sizeof=%2d   ", InpBuf0, sizeof(StrPtrArr[0]));
      strncpy_s(StrPtrArr[0], sizeof(StrPtrArr[0]), InpBuf0, _TRUNCATE);
      printf("strptrarr=%s\n", StrPtrArr[0]);
  
      StrPtrArr[1] = (char *)malloc(10 + 1);
      printf("inpbuf=%s   sizeof=%2d   ", InpBuf1, sizeof(*StrPtrArr[1]));
      strncpy_s(*StrPtrArr[1], sizeof(*StrPtrArr[1]), InpBuf1, _TRUNCATE);    //  error here
      printf("*strptrarr=%s\n", StrPtrArr[1]);
  
      free(StrPtrArr[0]);
      free(StrPtrArr[1]);
      free(StrPtrArr);
  
  
      return 0;
  }
  </code></pre>
  
  <p>The result I got was:</p>
  
  <pre><code>inpbuf=TstFld0   sizeof= 4   strptrarr=Tst
  inpbuf=TstFld1   sizeof= 1   
  </code></pre>
  
  <p>and the following error:</p>
  
  <pre><code>Exception thrown: write access violation.
  destination_it was 0xFFFFFFCD.
  </code></pre>
  
  <p>The result I thought I'd get was either of the following:</p>
  
  <pre><code>inpbuf=TstFld1   sizeof=11   *strptrarr=TstFld1
  inpbuf=TstFld1   sizeof= 1   *strptrarr=T
  </code></pre>
  
  <p>I understand the first copy copied the input buffer to the 4 byte pointer which was incorrect.  I thought the second copy would copy the input buffer to the value of the dereferenced pointer of a size of 11 but it didn't.  I'm guessing the copy was to the first character of the string in the array.  I don't understand memory enough to know the significance of the address 0xFFFFFFCD but I guess it's in read-only memory thus causing the error.</p>
  
  <p>What is the correct way to do the copy?</p>
  
  <p>(I don't think it matters, but I'm using VS 2015 Community Edition Update 3.)</p>