title: Overwriting dynamically allocated memory-C++
body: <p>I'm working on an assignment right now where we create our own basic, dynamically allocated vector struct. One of the functions we are supposed to make is a function to extend the vector when the user enters values. </p>
  
  <pre><code>struct Vector{//vector structure
      unsigned int size;
      Elem *svector;
  };
  
  Vector *extend_vec(Vector *extend,Elem element){
      if (extend==NULL){
          return NULL;}
  
  
      Elem *tempVec=new Elem[(*extend).size];
  
      memcpy(tempVec,(*extend).svector,sizeof((*extend).svector));//copies memory from the original array to the temp array
  
      (*extend).size+=1;
  
      delete[] (*extend).svector;//clears the memory
  
      (*extend).svector=new Elem[(*extend).size];//reallocates with the new size
  
  
  }
  </code></pre>
  
  <p>Elem=float btw**</p>
  
  <p>My question is whether this line is necessary, and why :</p>
  
  <pre><code> delete[] (*extend).svector;//clears the memory
  </code></pre>
  
  <p>I'm a bit hazy on how memory is overwritten/reallocated in a situation like this. I'm not sure if reallocating overwrites whats already there.</p>
  
  <p>**So I read through everyone's comments and this is what I came up with. </p>
  
  <pre><code>Vector *extend_vec(Vector *extend,Elem element){
      if (extend==NULL){
              return NULL;}
  
  
      Elem *tempVec=new Elem[extend-&gt;size+1];
      tempVec[extend-&gt;size+1]=element;
  
       memcpy(tempVec,extend-&gt;svector,(extend-&gt;size*sizeof(Elem)));//copies the memory from the original array to the rest of the temp array
  
      extend-&gt;size+=1;
  
      delete[] extend-&gt;svector;//clears the memory
  
      extend-&gt;svector=tempVec;//the original vector now becomes the extended vector
  
      delete[] tempVec;//clears the temporary memory
  
      return extend;
  }
  </code></pre>