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

标签 c malloc runtime-error bus-error

我正在尝试编译我用 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"));
}

你们有什么想法吗?谢谢!

最佳答案

while (str[i] != ' ') in count 如果没有遇到空格(例如在行尾),则超出字符串结尾。我看到你在多个地方犯了这个错误(在 extractsplit 中):你假设你会看到一个空格,但这不一定是真的。例如,您在 main 中传递的字符串的最后一个单词后面没有空格。

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

关于c - 在 C 中运行程序时出现总线错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50819248/

相关文章:

c++ - 运行 'make check' GLIBC 时出现链接问题

c++ - 运行时检查失败 #2 - 变量 "primes"周围的堆栈已损坏

java - ArrayAdapter.clear() 上的 NPE

vb6 - 将控件添加到集合会导致它们从控件数组中删除

c - 除非换行符在格式字符串中,否则为什么 printf 在调用后不刷新?

c - C : A struct and a function的命名约定

c - C : valgrind report shows additional allocs that can't be freed 中的线程

c - 程序的未定义行为。有时可以,有时运行时出错

c - realloc 2 dim 数组的段错误但输出正确?

c - 为char数组分配内存以连接已知的文本和整数