Search code examples
cmallocstrtokbus-error

Bus Error: 10 in C Program, cannot figure out why


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

void split_line(char **fields, char *line);

int main() {
    char *fields[5];
    char *line = "donuts,are,cool,and,tasty";
    int i = 0;

    split_line(fields, line);

    return 0;
}

void split_line(char **fields, char *line) {
    int i = 0;
    char *token, *delim;
    delim = ",\n";
    token = strtok(line, delim);
    while (token) {
        fields[i] = malloc(strlen(token));
        strcpy(fields[i], token);
        token = strtok(NULL, delim);
        i++;
    }

}

I am new to C and have been trying to figure out how to fix this error for the better part of an hour. It compiles but at run-time I get

Bus Error: 10.

I would appreciate if anyone could lead me to why this is happening and what I am doing wrong.


Solution

  • Because you can't modify a string literal, it's not legal. Try like this

    char line[] = "donuts,are,cool,and,tasty";
    

    Also, try to learn something other than strtok() for this without modifying the input string, because strtok() does that and it is why you are getting an error.

    As a recomendation, always use const for string literals

    const char *line = "donuts,are,cool,and,tasty";
    

    the compiler will help you see that you are trying to do something bad.

    Also, you malloc() 1 less character than you need. Strings need length characters + 1, the last character is the null terminator and it's always needed if you are going to use the data as a string, all the str functions expect this value to be there, so you need to allocate space for it, and copy it too

    size_t length = strlen(token);
    fields[i] = malloc(length + 1);
    if (fields[i] != NULL) {
        strcpy(fields[i], token);
    }