title: Using strcpy_s() and strcat_s() with dynamically allocated strings
body: <p>In the following code, I try to create a function that gets a dynamically allocated string. The function will ask the user to input another string that will also be dynamically allocated. Finally, you will allocate another large string to which the initial string will be copied, followed by the second string.</p>
  
  <p>My problem: In the function I use <code>strcpy_s()</code> and <code>strcat_s()</code> to copy and concatenate the strings and for a mysterious reason 2 functions override the program ...</p>
  
  <pre><code>#include&lt;iostream&gt;
  
  using namespace std;
  void addChars(char** theStr);
  
  void main()
  {
      // const def
      const int STR_SIZE = 10;
      char* str = new char[STR_SIZE + 1];
  
      cout &lt;&lt; "Enter 10 chars:" &lt;&lt; endl;
      cin.getline(str, STR_SIZE + 1);
  
      if (cin.fail())
      {
          cin.clear();
          cin.ignore(numeric_limits&lt;streamsize&gt;::max());
      }
  
      addChars(&amp;str);
  
      cout &lt;&lt; str &lt;&lt; endl;
  
      system("pause");
  }
  
  void addChars(char ** theStr)
  {
      int toAdd;
      int oldSize;
      char* AddStr;
      char* tempstr;
  
      cout &lt;&lt; "How many chars to add:" &lt;&lt; endl;
      cin &gt;&gt; toAdd;
      AddStr = new char[toAdd + 1];
  
      cout &lt;&lt; "Enter the chars: " &lt;&lt; endl;
      cin.clear();
      cin.ignore();
      cin.getline(AddStr, toAdd + 1);
  
      // check the src string size
      oldSize = strlen(*theStr);
  
      // alloc the big new str for the 2 exis strings
      tempstr = new char[(oldSize + toAdd) + 1];
  
      // copy the old string to the new
      strcpy_s(tempstr, oldSize, *theStr);
  
      // add the AddStr to the string
      strcat_s(tempstr, toAdd, AddStr);
  
      // delete the older and updates the new address
      delete[] * theStr;
      *theStr = tempstr;
  }
  </code></pre>