title: Heap corruption when making two bytes into a short. C++
body: <p>I am developing a program in C++ and encounter this error when I run this code:</p>
  
  <pre><code>short readshort() {
      short val=0;
      (&amp;val)[1]=data.front(); data.pop_front();
      (&amp;val)[0]=data.front(); data.pop_front();
      return val;
  }
  </code></pre>
  
  <p>This is the error I get:</p>
  
  <pre><code>Run-Time Check Failure #2 - Stack around the variable 'val' was corrupted.
  </code></pre>
  
  <p>I should mention now, that "data" is defined with std::list data;</p>
  
  <p>I think I know what is the problem, but I cannot think of an easy solution. I think this error is cause by the "val" being stored in the stack, and not as a pointer. When I try to access the data pointer by "val" I get this error.</p>
  
  <p>The solution I thought about was allocating "val" like this:</p>
  
  <pre><code>short readshort() {
      short* val=new short;
      val[1]=data.front(); data.pop_front();
      val[0]=data.front(); data.pop_front();
      return *val;
  }
  </code></pre>
  
  <p>But I can't see a way to delete "val" once I have returned it without having to delete it outside the function every time.
  Is there a way this can be done in C++ wihtout a memory leak? I havn't seen anyone split a variable type (e.g. short) into bytes using "(&amp;val)[1]" before, and wondered if this was because it gave rise to a number of problems, or is it just not a known method?</p>
  
  <p>Coming back to the real question, how can I make these two bytes into short (or large data type)? And is there a better way of doing this than what I have tried?</p>
  
  <p>One last thing, I know that java has an automatic garbage collector that cleans up memory leaks automatically. Does C++ offer the same kind of device? I heard somthing about Smart Pointers, but I don't know what they are ;)</p>