本文介绍了使用 strcpy、malloc 和 struct 时出现分段错误(核心转储)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,当我运行这段代码时,我遇到了分段错误:
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
", 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";
改为.
或者,为您的 char 分配内存,然后执行复制.注意:我绝不认可以下代码是好的,只是它会起作用.
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
", 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
", s->name);
free(s->name);
free(s);
return 0;
}
这篇关于使用 strcpy、malloc 和 struct 时出现分段错误(核心转储)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!