【发布时间】:2013-11-12 04:48:24
【问题描述】:
我是 C 的新手。抱歉,如果这个问题已经回答,我找不到直接的答案,所以我们开始吧..
我正在尝试了解 malloc() 在 C 中的工作原理。我有以下代码:
#define MAXLINE 100
void readInput(char **s)
{
char temp[MAXLINE];
printf("Please enter a string: ");
scanf("%s", temp);
*s = (char *)malloc((strlen(temp)+1)*sizeof(char)); // works as expected
//*s = (char *)malloc(2*sizeof(char)); // also works even when entering 10 chars, why?
strcpy ((char *)*s, temp);
}
int main()
{
char *str;
readInput(&str);
printf("Your string is %s\n", str);
free(str);
return 0;
}
问题是为什么当我这样调用 malloc() 时程序没有崩溃(或至少剥离剩余的字符):
*s = (char *)malloc(2*sizeof(char)); // also works even when entering 10 chars, why?
如果我输入一个超过两个字符的字符串,这不会导致缓冲区溢出吗?据我了解 malloc(),它为数据分配了一个固定空间,因此肯定只为两个字符分配空间将允许字符串最大为一个可用字符('0\' 是第二个),但它仍在打印输入的所有 10 个字符。
附:如果这有什么不同,我正在使用 Xcode。
谢谢, 西蒙
【问题讨论】:
-
因为你到达了“未定义的行为”领域。任何事情都可能发生......
-
另外,不要强制返回malloc:stackoverflow.com/questions/605845/…,而
sizeof(char)是多余的,malloc用char来计算分配数组的大小,所以根据定义sizeof(char)是一个。 -
感谢 Jens Gustedt!我也想知道类型转换。