title: C String Insertion Issues
body: <p>I'm trying to create a function that can insert a char array of length len into a given index in a string type. However, it acts ways that it shouldn't. </p>
  
  <p>When trying to insert at the end of the initial array, the contents of <code>buf</code> are inserted at the beginning of the string, in reverse order.</p>
  
  <p>i.e. inserting <code>world</code> into <code>Hello</code> becomes <code>dlrowHello</code></p>
  
  <p>When trying to insert in the middle of the initial case, the output is <code>worldHello</code></p>
  
  <p><code>str-&gt;bytes.data</code> is the array being modified.</p>
  
  <p><code>str-&gt;bytes.usage</code> is the length of that array.</p>
  
  <pre><code>bool string_insert(string_t * const str, size_t index, 
          const char * const buf, size_t len)
  {
      bool success = false;
      uint8_t orig_size = str-&gt;bytes.usage;
      uint8_t * temp;
  
      if (str-&gt;len &lt; index){
          return false;
      }
      if(str-&gt;bytes.usage+len&gt;=str-&gt;bytes.usage){
          temp = malloc(sizeof(char) * (str-&gt;bytes.usage + len));
      }   
      else {
          temp = malloc(sizeof(char) * (str-&gt;bytes.usage));
      }
      if (temp == NULL){
          success = false;    
      }
      else{
          if (index == 0){  //inserts at beginning
  
              for (int k = 0; k &lt; len; k++){
                  temp[k] = buf[k];
  
              }   
              for (int j = len; j &lt; str-&gt;bytes.usage+len; j++){
                  temp[j] = str-&gt;bytes.data[j - len];
              }
          }
          else if (index == str-&gt;bytes.usage){    //inserts at end
              for (int h = 0; h &lt; str-&gt;bytes.usage; h++){
                  temp[h] = str-&gt;bytes.data[h];
              }
              for (int g = 0; g &lt; len; g++){
                  temp[g+str-&gt;bytes.usage] = buf[g];  
              }
  
          }
          else{    //inserts in the middle
              for (int i = 0; i &lt; index; i++){
                  temp[i] = str-&gt;bytes.data[i];
              }
              for(int i = index; i &lt; index + len; i++){
                  temp[i] = buf[i-index];
              }
              for(int i = index + len; i &lt; str-&gt;bytes.usage+len; i++){
                  temp[i] = str-&gt;bytes.data[i-len];
              }
          }
          string_free(str);
          str-&gt;bytes.data = temp;
          str-&gt;bytes.dim = 2*str-&gt;bytes.usage;
          str-&gt;bytes.usage = orig_size+len;
          success = true;
      }
          return success;
  }
  </code></pre>
  
  <p>Basically, I just need to know if I'm blind and missing something obvious.</p>