当我使用strcpy、malloc和struct时,出现了分段错误(核心转储)。

5

好的,当我运行这段代码时,出现了分段错误:

#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

可以有人解释一下现在发生了什么吗?

1
你想让你的字符串大小为MAX吗? - Shafik Yaghmour
4个回答

4
您可能已经为结构体分配了内存,但没有为其字符指针分配内存。
您不能在未分配内存的情况下执行strcpy操作。您可以这样说
s->name = "Hello World"; 

或者,为您的字符分配内存,然后执行复制操作。 注意: 我绝不认可以下代码很好,只是它会起作用。

而不是使用realloc函数,你可以从堆中分配一个新块,将旧数据复制到新块中,并释放旧块。

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

编辑:这里提供了一种更简洁的实现方式,但我仍然不喜欢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;
}

1
你正在为结构体分配内存,但char *name仍然指向未初始化的内存。你需要为char *也分配内存。如果你想让它成为最大大小为64的字符串,在创建后可以更改,试试这个:
#include<stdio.h> 
#include<stdlib.h>
#include<string.h>
#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也会始终提供完全正确的大小。

0
struct example *s = malloc (MAX); 

这行代码将 s 指向一个能够容纳 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!");

0
问题在于你为 s 分配了内存,但没有为 s->name 分配内存,因此你正在对一个未初始化的指针进行间接引用,这是 未定义行为。假设你真的想要为一个 struct example 分配空间,并且你希望你的字符串大小为 MAX,那么你需要进行以下分配:
struct example *s = malloc (sizeof(struct example)); 
s->name = malloc(MAX*sizeof(char)) ;

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接