使用strcpy,malloc和struct 时,我有一个分段错误(核心转储)

好的,当我运行此代码时,我有一个分段错误:

#include #include #include #define MAX 64 struct example { char *name; }; int main() { struct example *s = malloc (MAX); strcpy(s->name ,"Hello World!!"); return !printf("%s\n", s->name); } 

终端输出:

 alshamlan@alshamlan-VGN-CR520E:/tmp/interview$ make q1 cc -Wall -g q1.c -o q1 alshamlan@alshamlan-VGN-CR520E:/tmp/interview$ ./q1 Segmentation fault (core dumped) alshamlan@alshamlan-VGN-CR520E:/tmp/interview$ gedit q1.c 

有人可以解释发生了什么吗?

您可能已为结构分配了内存,但没有为其字符指针分配内存。

您不能在未分配的内存上执行strcpy。 你可以说

 s->name = "Hello World"; 

代替。

或者,为您的char分配内存,然后执行复制。 注意 :我绝不赞同以下代码是好的,只是它会起作用。

 int main() { struct example *s = malloc(MAX); s->name = malloc(MAX); strcpy(s->name ,"Hello World!!"); return !printf("%s\n", s->name); } 

编辑:这可能是一个更干净的实现,但我仍然讨厌C风格的字符串

 #include #include #include #define KNOWN_GOOD_BUFFER_SIZE 64 typedef struct example { char *name; } MyExample; int main() { MyExample *s = (MyExample*) malloc( sizeof(MyExample) ); s->name = (char*) malloc(KNOWN_GOOD_BUFFER_SIZE); strcpy(s->name ,"Hello World!!"); printf("%s\n", s->name); free(s->name); free(s); return 0; } 

您正在为结构分配内存,但char *名称仍指向未初始化的内存。 您还需要为char *分配内存。 如果您希望它是最大大小为64的字符串,您可以在创建后更改,请尝试以下操作:

 #include #include #include #define MAX 64 struct example { char *name; }; int main() { struct example *s = malloc(sizeof(struct example)); s->name = malloc(MAX * sizeof(char)); strcpy(s->name ,"Hello World!!"); return !printf("%s\n", s->name); } 

注意我只将MAX分配给char *。 示例结构只需要是sizeof(struct example)),因此没有必要使它成为MAX。 这是一种更好的方法,因为即使您更改示例结构的成员,malloc也会继续为您提供完全正确的大小。

问题是你是为s分配内存而不是为s->name分配内存,所以你在未初始化的指针上执行间接操作,这是未定义的行为 。 假设您确实要为一个struct example分配空间并且希望字符串的大小为MAX那么您需要以下分配:

 struct example *s = malloc (sizeof(struct example)); s->name = malloc(MAX*sizeof(char)) ; 

请注意使用operator sizeof来确定要为其分配内存的数据类型的正确大小。

 struct example *s = malloc (MAX); 

该行指向能够容纳64个示例结构的存储器。 每个示例结构只有足够的内存来保存指针(称为名称)。

 strcpy(s->name ,"Hello World!!"); 

这是无效的,因为s-> name没有指向任何地方,它需要指向已分配的内存。

你可能想要:

 struct example *s = malloc(sizeof(struct example)); //Allocate one example structure s->name = malloc(MAX); //allocate 64 bytes for name strcpy(s->name,"Hello world!"); //This is ok now. 

这与:

 struct example s; //Declare example structure s.name = malloc(MAX); //allocate 64 bytes to name strcpy(s.name,"Hello world!");