简体   繁体   中英

Segmentation fault for function to split the words of a string in a 2d string

I am trying to write a function who take a string and puts all the words in a 2d array, but I am getting a Segmentation fault error.

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

static int      ft_countwords(char const *s, char c)
{
    int     nbr;
    int     i;

    i = 0;
    nbr = 0;
    while (s[i])
    {
        if (s[i] != c) 
        {
            nbr++;
            while (s[i] != c)
                i++;
        }
        else
        {
            while (s[i] == c)
                i++;
        }   
    }
    return (nbr);
}

static char     *ft_getword(char const *s, char c, int *start)
{
    int     i;
    int     word_size;
    char    *word;

    i = 0;  
    word_size = *start;
    while (s[word_size] && s[word_size] != c)
        word_size++;
    word = (char*)malloc(word_size - *start + 1);
    while (s[*start] && s[*start] != c)
    {
        word[i] = s[*start];
        i++;
        *start++;
    }
    word[i] = '\0';
    return (word);
}

char            **ft_strsplit(char const *s, char c)
{
    int     row;
    int     i;
    char    **a;

    a = NULL;
    if (s)
        a = (char**)malloc(sizeof(char*) *  ft_countwords(s, c) + 1);
    row = 0;
    i = 0;
    while (s[i] && row < ft_countwords(s, c))
    {
        if (s[i] != c && s[i])
        {
            a[row] = strdup(ft_getword(s, c, &i));
            row++;
        }
        while (s[i] == c)
            i++;
    }
    a[row] = '\0';
    return (a);
}
int             main(void)
{
    int     i;
    char    *test, **a;

    test = strdup("__AAA_bbb__ccccc_DDDD___");
    a = ft_strsplit((char const *)test, '_');
    if (a)
    {
        i = 0;
        while (a[i])
        {
            printf("%s\n", a[i]);
            i++;
        }
    }
    else
        printf("(null)");
    return (0);
}

I tested the first two functions and they work, but I cannot find the problem with the ft_strsplit function.

gcc ft_strsplit.c && ./a.out
Segmentation fault (core dumped)

Recompile with -g to get debugging information in your core dump. Then use gdb to analyze the core dump. You can get a backtrace with where and then you can use print to see the values of variables. You should be able to identify the problem from there.

Alternatively, add a lot of logging to your program to figure out what it's doing just before it crashes and you should be able to keep narrowing it down until you find the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM