title: C - dynamical allocation/rellocation inside the function
body: <p>I have written this function in C (function should receive a <code>char*</code>, allocate space necessary, and insert character given a pointer to the index of character behind the pointer)</p>
  
  <pre><code>void add_to_str(char *character, char ** string, int* index)
  {
      //we dont expect  *string to be NULL !! no condition done
      if (*index == 0)    //if str is empty we will alloc AVGLEN(32) characters space
         *string=malloc(AVGLEN*sizeof(char));
  
      if (*string == NULL)   //malloc fails?
      {
          fprintf(stderr,errors[MALLOC]);
          exit(99);
      }
      //string length exceeds 32 characters we will allocate more space
      if ( *index &gt; (AVGLEN-1) || character== NULL )// or string buffering ended, we will free redundant space
      {
          *string=realloc(*string,sizeof(char)*((*index)+2));//+1 == '\0' &amp; +1 bcs we index from 0
          if (*string==NULL)   //realloc fails?
          {
              fprintf(stderr,errors[REALLOC]);
              exit(99);
          }
      }
      *string[(*index)++]=*character;
  }
  </code></pre>
  
  <p>When <code>*index &gt; 0</code>, it gives me a segmentation fault on the line</p>
  
  <pre><code>*string[(*index)++]=*character;
  </code></pre>
  
  <p>A variant of this function (just <code>malloc</code> behind <code>char*</code> and then assign characters to <code>string[i++]</code>) works perfectly.</p>