Segmentation fault, I don’t know why

I would recommend you to replace

if(c!=' ' && c!='\t' && c!='\n')

with

if(!isspace(c))  // Iam easier and more readable

from ctype.h. Which detects all these characters

' '      space 
'\t'     horizontal tab 
'\n'     newline
'\v'     vertical tab 
'\f'     feed 
'\r'     carriage return

Also you should change char*** word_array; (three star general) to pointer to pointer which is enough. Then alloc memory on heap (dynamic storage duration). You didnt do it and it caused segmentaion fault (dereferencing uninitialzed pointer).

char ** word_array = malloc (sizeof(char *) * ROWS);
for (int i = 0; i < ROWS; ++i)
{
    word_array[i] = malloc (sizeof(char) * ROW_LEN);
}

You shouldn’t cast malloc()‘s return value because it may lead to problems.

Also you should check number of rows, and if needed use realloc to get more rows, because accessing out of bounds leads to undefined behavior.


Instead of copying character by character use strcpy, since you know there is enough space. Its more readable and easier.

for(k=0 ; tmp[k] != '\0' ; k++){
    (*word_array)[j][k]=tmp[k];
}

to

strcpy(word_array[j], tmp); // In case word_array is char **

I can see spaces in your string but you arent skiping them, this may help

while ((c=s[id_s++]) && isspace(c))
    ;

Leave a Comment