c - strncpy issue

Posted by Joe on Stack Overflow See other posts from Stack Overflow or by Joe
Published on 2010-04-07T15:40:02Z Indexed on 2010/04/07 15:43 UTC
Read the original article Hit count: 400

Filed under:

Hi there,

I am getting segmentation fault when using strncpy and (pointer-to-struct)->(member) notation:

I have simplified my code. I initialise a struct and set all of it's tokens to an empty string. Then a declare a pointer to a struct and assign the address of the struct to it.

I pass the pointer to a function. I can print out the contents of the struct at the beginning of the function, but if I try to use the tp -> mnemonic in a strncpy function, I get seg fault. Can anyone tell me what I am doing wrong?

typedef struct tok  {
    char* label;
    char* mnem;
    char* operand;
}Tokens;

Tokens* tokenise(Tokens* tp, char* line)  {
    // This prints fine
    printf("Print this - %s\n", tp -> mnem);

    // This function gives me segmentation fault
    strncpy(tp -> mnem, line, 4);

    return tp;
}

int main()  {
    char* line = "This is a line";
    Tokens tokens;
    tokens.label = "";
    tokens.mnem = "load";
    tokens.operand = "";

    Tokens* tp = &tokens;
    tp = tokenise(tp, line);

    return 0;
}

I have used printf statements to confirm that the code definitely stops executing at the strncpy function.

Can anyone tell me where I am going wrong?

Many thanks

Joe

© Stack Overflow or respective owner

Related posts about c