代码之家  ›  专栏  ›  技术社区  ›  Wizzardzz

在C中运行程序时出现总线错误

  •  0
  • Wizzardzz  · 技术社区  · 6 年前

    我试图编译一个用C语言编写的程序,但是 运行程序时无法消除“总线错误”。 我遇到了其他提到“字符串文本”和内存问题的线程,但我认为是时候重新审视我的代码了。

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

    数字数:

    int     count(char *str)
    {
        int i = 0;
        int k = 0;
    
        while (str[i])
        {
            if (str[i] != ' ')
            {
                while (str[i] != ' ')
                    i++;
                k++;
            }
            else
                i++;
        }
        return (k);
    }
    

    提取单词:

    void    extract(char *src, char **dest, int i, int k)
    {
        char    *tabw;
        int     j = 0;
    
        while (src[i + j] != ' ')
            j++;
    
        tabw = (char*)malloc(sizeof(char) * j + 1);
    
        j = 0;
    
        while (src[i + j] != ' ')
        {
            tabw[j] = src[i + j];
            j++;
        }
    
        tabw[j] = '\0';
        dest[k] = &tabw[0];
    
        return;
    }
    

    将字符串拆分为单词:

    char    **split(char *str)
    {
        int     i = 0;
        int     k = 0;
        char    **dest;
    
        dest = (char**)malloc(sizeof(*dest) * count(str) + 1);
    
        while (str[i] != '\0')
        {
            while (str[i] == ' ')
                i++;
    
            if (str[i] != ' ')
                extract(str, dest, i, k++);
    
            while (str[i] != ' ')
                i++;
        }
        dest[k] = 0;
        return (dest);
    }
    

    印刷:

    void    ft_putchar(char c)
    {
        write(1, &c, 1);
    }
    
    void    print(char **tab)
    {
        int     i = 0;
        int     j;
    
        while (tab[i])
        {
            j = 0;
            while (tab[i][j])
            {
                ft_putchar(tab[i][j]);
                j++;
            }
            ft_putchar('\n');
            i++;
        }
    }
    
    int     main()
    {
        print(split("  okay  blue     over"));
    }
    

    你们知道吗?谢谢!

    1 回复  |  直到 6 年前
        1
  •  2
  •   Paul Ogilvie    6 年前

    while (str[i] != ' ') 在里面 count 如果没有遇到空格(例如行尾),则超出字符串结尾。我看到你在很多地方都犯了这个错误 extract split ):假设您将看到一个空格,但这不一定是正确的。例如,您传入的字符串的最后一个字 main 后面不是空格。

    用途: while (str[i] != ' ' && str[i] != 0 )