简体   繁体   English

将字符串的单词拆分为二维字符串的函数的分段错误

[英]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.我测试了前两个函数并且它们可以工作,但是我找不到 ft_strsplit 函数的问题。

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

Recompile with -g to get debugging information in your core dump.使用-g重新编译以获取核心转储中的调试信息。 Then use gdb to analyze the core dump.然后使用gdb来分析core dump。 You can get a backtrace with where and then you can use print to see the values of variables.您可以使用where获得回溯,然后您可以使用print查看变量的值。 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.或者,向您的程序添加大量日志记录,以在程序崩溃之前弄清楚它在做什么,并且您应该能够继续缩小范围,直到找到问题为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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