cmallocruntime-errorbus-error

Bus error running a program in C


I am trying to compile a program I wrote in C but can't get rid of a 'bus error' when running the program. I came across other threads mentioning 'string literals' and memory issues but I think it's time I ask for a fresh look over my code.

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

Counting the words:

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

Extracting the words:

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

Splitting the string into words:

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

Printing:

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

Do you guys have any idea? Thanks!


Solution

  • while (str[i] != ' ') in count goes beyond end-of-string if no space is encountered (e.g. at end of line). I see you make this mistake at multiple places (in both extract and split): you assume you will see a space, but that is not necessarily true. For example, the last word of the string you pass in main is not followed by a space.

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