簡體   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