You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何未用malloc分配内存时,strcpy结果存入plates[idx]会触发段错误?

为什么使用strcpy前必须为指针分配内存?

问题场景

第一段代码编译运行时触发segmentation fault (core dumped)错误:

char buffer[7];

// Create an array to store plate numbers
char *plates[8];

FILE *infile = fopen(argv[1], "r");

int idx = 0;

while (fread(buffer, 1, 7, infile) == 7)
{
    // Replace '\n' with '\0'
    buffer[6] = '\0';

    // Save the plate number in the array
    plates[idx] = strcpy(plates[idx], buffer);
    idx++;
}

用户尝试将buffer中的内容通过strcpy存入字符指针数组plates的元素plates[idx],但未提前为plates[idx]分配内存;而第二段代码通过malloc为plates[idx]分配7字节内存后即可正常运行:

// Create a buffer to read into
char buffer[7];

// Create an array to store plate numbers
char *plates[8];

FILE *infile = fopen(argv[1], "r");

int idx = 0;

while (fread(buffer, 1, 7, infile) == 7)
{
    // Replace '\n' with '\0'
    buffer[6] = '\0';

    // Save plate number in array
    plates[idx] = malloc(sizeof(char) * 7);
    plates[idx] = strcpy(plates[idx], buffer);
    idx++;
}

用户疑问:为何必须先为plates[idx]分配指定大小的内存,才能使用strcpy存储结果?

原因解释

  • char *plates[8]是一个指针数组,数组里的每个元素plates[idx]都是char*类型的指针,但这些指针声明后并未初始化,指向的是内存中的随机地址——要么是程序无权访问的区域,要么是存储其他重要数据的区域。
  • strcpy(dest, src)的核心逻辑是把src指向的字符串完整复制到dest指向的内存空间中,这要求dest必须指向一块已分配完成、且容量足够容纳整个字符串(包括末尾的终止符\0)的合法内存区域。
  • 第一段代码里,plates[idx]属于未初始化的野指针,strcpy尝试将buffer的内容写入这个随机地址时,要么直接触发内存访问权限错误(也就是你遇到的段错误),要么覆盖了其他程序数据导致异常。
  • 第二段代码通过malloc(sizeof(char)*7)申请了7字节的合法内存,plates[idx]指向这块内存后,strcpy就有了合规的目标存储区域,自然能正常完成字符串复制操作。

内容的提问来源于stack exchange,提问作者Trying90

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:53:22