分割断层的strcpy() [英] Segmentation Fault in strcpy()

查看:154
本文介绍了分割断层的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;
}

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

推荐答案

您的typedef定义汽车结构来袭* ,即一个指针。所以,它的大小将是 4 8 依赖于架构,而不是结构的大小

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

使用的sizeof(*卡车)来获得结构的实际大小。

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

您还需要为角色分配内存。最简单的方法将使用的strdup()

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


不过,我建议改变你的typedef所以它的结构的别名,而不是一个指向它:


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

这篇关于分割断层的strcpy()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆