title: How to allocate and return a string without memory leak in C++?
body: <p>Let's say I have 3 functions:</p>
  
  <pre><code>int A(void); 
  string B(const string&amp; fileName); 
  void C(string&amp; dataFromFile);
  </code></pre>
  
  <p>A() calls B() and uses B()'s return value as an input parameter to C(). In this case, I want to open the file in B() and read the data written in the file to a buffer. Then I want to return this data as a string. How can I implement B() to avoid memory leak? Because the pseudo-code below would cause memory leak.</p>
  
  <pre><code>string B(const string&amp; fileName) {
      // open file 
      char* buffer = new char[sizeOfFile];
      // read from file and assogn the data to buffer
      return buffer;
  }
  </code></pre>