title: Segmentation fault (11) when using malloc inside a function to form a string
body: <p>I'm trying to use a function to assign space and fill that space (or at least some of it) with characters to form a string. Within the function I make a call to malloc, and within the same function I assign characters to the given space. The following code gives the general gist of what I'm doing:</p>
  
  <pre><code>#define INITIAL 10
  
  int func(char **s);
  
  int
  main(int argc, char **argv) {
      char *s;
      int n;
  
      n = func(&amp;s);
      printf("Done\n");
  
      return 0;
  }
  
  int
  func(char **s) {
      int i;
  
      *s = (char*)malloc(INITIAL*sizeof(char));
      assert(*s);
  
      for (i=0; i&lt;5; i++) {
          printf("i=%d\n", i);
          *s[i] = 'a'; /*'a' is an arbitrary char for this example */  
      }
      return i;    
  }
  </code></pre>
  
  <p>The output of this code is:</p>
  
  <pre><code>i=0
  i=1
  i=2
  Segmentation fault: 11
  </code></pre>
  
  <p>The reason I have my function return an int is because I ultimately want the function to return the length of the string I have formed.<br>
  I'm completely unsure why I am getting a segmentation fault; it seems I have assigned enough space to fit the next char in. It also seems weird to me that it stops at i=2.
  If anyone could identify the mistakes I have made I would greatly appreciate it! </p>