繁体   English   中英

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

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

我正在尝试编写一个函数,该函数接受一个字符串并将所有单词放入一个二维数组中,但是我收到了一个分段错误错误。

#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);
}

我测试了前两个函数并且它们可以工作,但是我找不到 ft_strsplit 函数的问题。

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

使用-g重新编译以获取核心转储中的调试信息。 然后使用gdb来分析core dump。 您可以使用where获得回溯,然后您可以使用print查看变量的值。 您应该能够从那里确定问题。

或者,向您的程序添加大量日志记录,以在程序崩溃之前弄清楚它在做什么,并且您应该能够继续缩小范围,直到找到问题为止。

暂无
暂无

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

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