strcpy() 中的分段错误 [英] Segmentation Fault in strcpy()

查看:31
本文介绍了strcpy() 中的分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的基本结构

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 中遇到错误.它编译没有问题.

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

推荐答案

你的 typedef 将 Truck 定义为 struct seen *,即一个指针.所以它的大小将是 48 取决于架构而不是结构的大小

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(*Truck) 获取结构体的实际大小.

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天全站免登陆