我使用的strcpy,malloc和结构时,可以有段故障(核心转储) [英] I have a segmentation fault (core dumped) when using strcpy, malloc, and struct
本文介绍了我使用的strcpy,malloc和结构时,可以有段故障(核心转储)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好吧,当我运行这个code,我有一个分段错误:
Okay, when I run this code, I have a segmentation fault:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#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
有人能解释这是怎么回事?
Can someone explain what's going on?
推荐答案
您可能已经分配的内存为你的结构,而不是它的字符指针。
You may have allocated memory for your struct, but not for its character pointer.
您不能执行的strcpy到存储器上的未分配。你可以说
You can't perform a strcpy onto memory that isn't allocated. You could say
s->name = "Hello World";
代替。
另外,对于您的字符分配内存,然后再进行复制。
注意:我绝不赞同以下code是不错的,只是它会工作
Alternatively, allocate memory for your char, and then perform the copying. NOTE: I in NO way endorse that the following code is good, just that it will work.
int main()
{
struct example *s = malloc(MAX);
s->name = malloc(MAX);
strcpy(s->name ,"Hello World!!");
return !printf("%s\n", s->name);
}
编辑:这也许是一个更清洁的实现,但我仍然讨厌C风格的字符串
Here is perhaps a cleaner implementation, but I still hate C-style strings
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#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;
}
这篇关于我使用的strcpy,malloc和结构时,可以有段故障(核心转储)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文