strcpy()中的分段错误

时间:2012-04-13 15:15:20

标签: c segmentation-fault strcpy

我有一个像这样的基本结构

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

这样的功能会创建该结构的新“实例”:

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

我在第一个strcpy收到错误。它编译没有问题。

3 个答案:

答案 0 :(得分:11)

您的typedef将Truck定义为struct struck *,即指针。所以它的大小将是48,具体取决于体系结构而不是结构的大小

使用sizeof(*Truck)获取结构的实际大小。

您还需要为角色分配内存。最简单的方法是使用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;
}

但是,我建议更改你的typedef,这样它就是struct的别名,而不是指向它的指针:

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

在你的功能中,你可以使用它:

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

答案 1 :(得分:7)

nT->id只是一个指针。需要malloc内存来复制字符串。与其他人一样。

答案 2 :(得分:4)

您对sizeof的使用不正确。通常,malloc()的参数必须是“返回指针指向的大小”。换句话说,您需要sizeof *nT。看看如何消除重复类型名称(Truck)?

另外,在C中don't need to cast the return value of malloc();它没有任何意义,可以隐藏实际错误,并使代码更难阅读。

正如其他人所指出的那样,你也没有为任何字符串数据分配空间,你所拥有的只是你结构中的指针。