-7

I have a seg fault but I don't know why. I know it should be working but it kee telling me there is a seg fault someone has a solution? Please someone help I need to know for my BA.

#include <stdio.h>
#include <stdlib.h>

int split_allocate(const char* s, char*** word_array){
    char c;
    char tmp[100];
    int id_s,i=0, j=0,k;
    for(id_s =0 ; (c=s[id_s])!='\0' ; id_s++){
        printf("%c\n", c);
        if(c!=' ' && c!='\t' && c!='\n'){
            tmp[i]=c;
            i++;
            printf("i if : %d\n", i);
            continue;
        }
        tmp[i]='\0';
        printf("i else : %d & tmp : %s\n", i, tmp);
        (*word_array)[j] = (char*)malloc(sizeof(char)*(i+1));
        printf("666\n");
        if(NULL== (*word_array)[j]){
            return -1;
        }
        for(k=0 ; tmp[k] != '\0' ; k++){
            (*word_array)[j][k]=tmp[k];
        }
        (*word_array)[j][k+1]='\0';
        j++;
        printf("j for : %d\n", j);
        i=0;
    }
    return j;
}

int main(void) {
    char* s = "Salut,   cet examen\n a l'air long...";
    char*** word_array;
    printf("number of words :%d\n", split_allocate(s,word_array));
    return 0;
}
dbush
  • 205,898
  • 23
  • 218
  • 273
Sam45505
  • 11
  • 1

1 Answers1

1

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))
    ;
kocica
  • 6,412
  • 2
  • 14
  • 35