I'm stuck with an unidentified Segmentation Fault.
My erroneous function receives a string text
. It should convert it into a document
and return it. A document
is made of paragraphs
(separated by '\n') which is made of sentences
(separated by '.') which is made of words
(separated by ' '). You may refer the complete problem statement here.
Here is the relevant part of my 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;
}
After debugging, I came to know that the program crashes when
w = 1 at document[p][s][w][c - 1] = *text;
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.
But in vain!
What might be going wrong in my code?