使用 strcpy、malloc 和 struct 时出现分段错误(核心转储)[重复]

2023-11-30

好吧,当我运行这段代码时,我遇到了分段错误:

#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

有人能解释一下发生了什么事吗?


您可能已经为结构分配了内存,但没有为其字符指针分配内存。

您无法对未分配的内存执行 strcpy。你可以说

s->name = "Hello World"; 

instead.

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

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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 strcpy、malloc 和 struct 时出现分段错误(核心转储)[重复] 的相关文章

随机推荐