首页 > 解决方案 > 在 C 中运行程序的总线错误

问题描述

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

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

标签: cmallocruntime-errorbus-error

解决方案


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

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


推荐阅读