Bus Error with strncpy in C

566 Views Asked by At

I am working on the same project as in this question, however with a slightly different typedef:

typedef struct {
    char* word;
    int index;
} data_t;

typedef struct node node_t;

typedef node {
    void *data;
    node_t *left;
    node_t *right;
}

I am trying to split a string into individual words, sticking it into the data_t struct and then inserting it into a binary search tree. The idea is that, while looping across an input string, when it is found that the character is one which marks the end of a word, the number of characters between the start and end of the word is copied into a string, which I have attempted to do using:

strncpy(newstring, (in+wordstart), (i-wordstart));

where:

char* newstring, in;
int i, wordstart;

However, gcc gives a bus error when that particular line is called. How this bus error can be fixed and the current solution kept, or would it be wiser to look for a different solution?

The only idea I have been able to think of so far is to, one character at a time, put the characters into the string until the end of the word has been reached.

2

There are 2 best solutions below

2
On

This doesn't declare two pointers, this is just one pointer and a char

char* newstring, in;

It should be declared like this:

char *newstring, *in;

Also, as someone else noted, it doesn't seem that you're allocating any memory for those pointers.

0
On

This:

typedef node {
    void *data;
    node_t *left;
    node_t *right;
}

doesn't make any sense at all. There's no struct keyword before the node, and no name for the type alias you're trying to introduce after the }, and no terminating semi colon. This shouldn't compile.