title: Hackerrank: C - Querying the Document
body: <p>I'm stuck with an unidentified Segmentation Fault.</p>
  
  <p>My erroneous function receives a string <code>text</code>. It should convert it into a <code>document</code> and return it. A <code>document</code> is made of <code>paragraphs</code>(separated by <em>'\n'</em>) which is made of <code>sentences</code>(separated by <em>'.'</em>) which is made of <code>words</code>(separated by <em>' '</em>). You may refer the complete problem statement <a href="https://www.hackerrank.com/challenges/querying-the-document/problem" rel="nofollow noreferrer">here</a>.</p>
  
  <p>Here is the relevant part of my code:</p>
  
  <pre><code>char**** get_document(char* text) {
      int p = 0, s = 0, w = 0, c = 0;
      char**** document;
      document = malloc(sizeof(char***));
      document[0] = malloc(sizeof(char**));
      document[0][0] = malloc(sizeof(char*));
      document[0][0][0] = malloc(sizeof(char));
      while (*text)
      {
          if (*text == ' ')
          {
              c = 0;
              ++w;
              document[p][s] = realloc(document[p][s], sizeof(char*) * (w + 1));
          }          
          else if (*text == '.')
          {
              c = 0;
              w = 0;
              ++s;
              document[p] = realloc(document[p], sizeof(char**) * (s + 1));
          } 
          else if (*text == '\n')
          {
              c = 0;
              w = 0;
              s = 0;
              ++p;
              document = realloc(document, sizeof(char***) * (p + 1));
          }
          else
          {
              ++c;
              document[p][s][w] = realloc(document[p][s][w], sizeof(char) * (c + 1));
              document[p][s][w][c - 1] = *text;
              document[p][s][w][c] = '\0';
          }
          ++text;
      }
      return document;
  }
  </code></pre>
  
  <p>After debugging, I came to know that the program crashes when</p>
  
  <p><strong>w = 1</strong> at <code>document[p][s][w][c - 1] = *text;</code></p>
  
  <p>I have no idea why this is happening. I checked the values of p, s, w, and c before the execution of that statement, and if the realloc statements were executing properly.</p>
  
  <p>But in vain!</p>
  
  <p>What might be going wrong in my code?</p>