title: Swift UnsafeMutablePointer memory allocation and deallocation in a function
body: <p>I am programming using Swift 2.2 on Mac OS X 10.11.  I have a function that looks like this:</p>
  
  <pre><code>func aFunction(direntPointer: UnsafePointer&lt;dirent&gt;, usingBuffer bufPointer: UnsafeMutablePointer&lt;CChar&gt;) {
      let tempBuf = UnsafeMutablePointer&lt;CChar&gt;.alloc(2048)
  
      ... [put the filename from the dirent into tempBuf and do some processing]
  
      // Transfer the data in the temporary buffer into the provided buffer
      bufPointer.moveAssignFrom(tempBuf, count: 2048)
  
      // Seems necessary, but destroys the data in bufPointer as well
      tempBuf.dealloc(2048)
  
      return
  }
  </code></pre>
  
  <p>The bufPointer is set up in a calling function as:</p>
  
  <pre><code>let bufPointer = UnsafeMutablePointer&lt;CChar&gt;.alloc(2048)
  </code></pre>
  
  <p>Upon return to the calling routine, bufPointer does not contain valid data.  However, if I remove the tempBuf.dealloc() method call, then tempBuf contains valid memory and the routine works as expected.  According to the literature, the moveAssignFrom() method destroys the source memory more efficiently that doing a separate move() and then destroy().</p>
  
  <p>My question is whether the dealloc() method call is necessary to avoid a memory leak or if it does not matter because it is being created on the stack and is just being destroyed upon return?  The Apple literature says that allocated memory needs to be deallocated, but I cannot return valid data if it is deallocated.</p>
  
  <p>Perhaps there is a better way to do this?  The purpose of the function call is to consolidate the code to avoid repeating it because it is being called from multiple places, and to process the filename that is retrieved from the dirent.</p>
  
  <p>Thank you</p>