gpt4 book ai didi

c - (char*)malloc(sizeof(char)) 分配多个字符?

转载 作者:行者123 更新时间:2023-11-30 20:48:40 25 4
gpt4 key购买 nike

我在理解内存如何分配给 sir[i] 时遇到了一些困难。据我了解(char*)malloc(sizeof(char))应该只为一个字符分配空间,但是当我运行代码时,它可以读取任何单词,无论长度如何。有人可以解释一下这是如何/为什么会发生吗?

void read(char **sir,int **ln,int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Read word %d: ",i+1);
sir[i]=(char*)malloc(sizeof(char));
fflush(stdin);
scanf("%s",sir[i]);
ln[i]=(int*)malloc(sizeof(int));
*(ln[i])=strlen(sir[i]);
}
}

最佳答案

您的写入超出了您分配的内存范围。这是未定义的行为,而且你很不幸它似乎“有效”。

关于c - (char*)malloc(sizeof(char)) 分配多个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34895868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com