mal*_*002 5 c 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);
}
Run Code Online (Sandbox Code Playgroud)
终端输出:
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
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下发生了什么事吗?
您可能已经为结构分配了内存,但没有为其字符指针分配内存。
您无法对未分配的内存执行 strcpy。你可以说
s->name = "Hello World";
Run Code Online (Sandbox Code Playgroud)
反而。
或者,为您的字符分配内存,然后执行复制。 注意:我绝不认可以下代码是好的,只是它可以工作。
int main()
{
struct example *s = malloc(MAX);
s->name = malloc(MAX);
strcpy(s->name ,"Hello World!!");
return !printf("%s\n", s->name);
}
Run Code Online (Sandbox Code Playgroud)
编辑:这也许是一个更干净的实现,但我仍然讨厌 C 风格的字符串
#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;
}
Run Code Online (Sandbox Code Playgroud)