C语言 我在使用 strcpy、malloc 和 struct 时出现分段错误(核心转储)



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

#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("%sn", 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("%sn", 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("%sn", s->name);
  free(s->name);
  free(s);
  return 0;
}

您正在为结构分配内存,但 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("%sn", s->name);
}

请注意,我仅将 MAX 分配给字符 *。示例结构只需要是 sizeof(结构示例)),所以没有必要让它成为 MAX。这是一种更好的方法,因为即使您更改示例结构的成员,您的 malloc 也会继续为您提供确切的正确大小。

问题是

您正在为s分配内存,而不是为s->name分配内存,因此您正在对未初始化的指针执行间接寻址,这是未定义的行为。假设您确实希望为一个struct example分配空间,并且希望字符串的大小为 MAX,则需要以下分配:

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

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

struct example *s = malloc (MAX); 

这条线指向一个能够容纳64个示例结构的存储器。每个示例结构只有足够的内存来保存指针(称为 name)。

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!");

最新更新