title: How to return a char array created in function?
body: <p>I've been programming badly for quite a while and I only really just realised. I have previously created many functions that return character strings as char arrays (or at least pointers to them).</p>
  
  <p>The other day someone pointed out that when my functions return the char arrays pointed to by my functions have gone out of scope and I'm essentially now pointing to a random bit of memory (A nasty dangling pointer).</p>
  
  <p>I didn't really notice this for a while because the char arrays when outputted to the console didn't appear to be corrupt (probably because there wasn't time for that data to be overwritten). I did however notice this when I was returning a string buffer (char array) generated by reading the serial port which was frequently corrupt.</p>
  
  <p>So, how best should I do it?</p>
  
  <p>My bad code is as follows:</p>
  
  <pre><code>#include &lt;cstdlib&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  char* myBadFunction(){
      char charArray[] = "Some string\n";
      char* charPointer = charArray;
      return charPointer;
  }
  
  
  int main(int argc, char** argv) {
  
      cout &lt;&lt; myBadFunction();
  
      return 0;
  }
  </code></pre>
  
  <p>I understand that I should perhaps allocate memory in the program before calling the function or create a global variable to put the returned string in, but if my called function is used by many different programs when how should it know the size of the buffer being passed into it in advance and when should this memory be deleted?</p>
  
  <p>The following code also doesn't do what I want it to properly:</p>
  
  <pre><code>#include &lt;cstdlib&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  void fillArray(char* charPointer){
      char charArray[] = "Some string\n"; // Create string
      charPointer = charArray; // Not correct, want to fill predefined array with created string
      return;
  }
  
  
  int main(int argc, char** argv) {
  
      char predefinedArray[50] = {0};
      fillArray(predefinedArray);
      cout &lt;&lt; predefinedArray;
  
      return 0;
  }
  </code></pre>
  
  <p>I want to fill the array that the pointer parsed points to but this doesnt' happen in the code above.</p>
  
  <p>Also, when should I use the new[] command to create my array? is it needed? and when should I call delete[] on it.</p>
  
  <p>Many thanks for this, its obviously very fundamental but something I've been doing wrong for a while.</p>