Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

c - Segmentation Fault in strcpy()

I have a basic structure like this

typedef struct struck {
    char* id;
    char* mat;
    int value;
    char* place;
} *Truck;

And afunction like this which creates a new "instance" of that struct:

Truck CTruck(char* id, char* mat, int value, char* place) {
    Truck nT = (Truck) malloc(sizeof (Truck));
    nT->value = value;
    strcpy(nT->id, id);
    strcpy(nT->mat, mat);
    strcpy(nT->place, place);
    return nT;
}

I'm getting an error in the first strcpy. It compiles without problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your typedef defines Truck as a struct struck *, i.e. a pointer. So it's size will be 4 or 8 depending on the architecture and not the size of the struct

Use sizeof(*Truck) to get the actual size of the struct.

You also need to allocate memory for the characters. The easiest way would be using strdup().

Truck CTruck(const char* id, const char* mat, int value, const char* place) {
    Truck nT = malloc(sizeof (*Truck));
    nT->value = value;
    nT->id = strdup(id);
    nT->mat = strdup(mat);
    nT->place = strdup(place);
    return nT;
}

However, I would suggest changing your typedef so it's an alias for the struct, not for a pointer to it:

typedef struct {
    char* id;
    char* mat;
    int value;
    char* place;
} Truck;

In your function you then use this:

Truck *nT = malloc(sizeof(Truck));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...