这个malloc不应该工作 [英] This malloc shouldn't work
问题描述
这是我的代码.
int main()
{
char *s;
int i = 0;
printf("%lu \n", sizeof(s));
s = malloc(sizeof(char) * 2);
printf("%lu \n", sizeof(s));
/*Why is this working?*/
while (i <= 5)
{
s[i] = 'l';
i++;
}
printf("%s \n", s);
printf("%lu \n", sizeof(char));
printf("%lu \n", sizeof(s[0]));
}
在我看来,这应该是段错误,因为我尝试编写的内容超出了我的分配范围.为什么这样做有效?
In my opinion, this should segfault as I'm trying to write more than I allocated. Why is this working?
推荐答案
示例 (并完全同意)@Ed S的答案 ,请尝试在您的代码示例中添加一小部分附加变量,这些附加变量的声明方式完全相同,并在char *s
之后进行malloc.
In illustration (and complete agreement with) @Ed S's answer, Try this example of your code with the small additions of an additional variable declared exactly the same way and malloc'ed right after the char *s
.
尽管不能保证 将变量顺序存储在内存中,但以这种方式创建变量的可能性很高. 如果是,则char *t
现在将拥有char *s
将会占用的空间,并且您将遇到段错误:
Although no guarantees that the variables are stored sequentially in memory, creating them this way makes it a high probability. If so, char *t
will now own the space that char *s
will encroach on, and you will get a seg fault:
int main()
{
char *s;
char *t;//addition
int i = 0;
printf("%lu \n", sizeof(s));
s = malloc(sizeof(char) * 2);
t = malloc(sizeof(char) * 2);//addition
printf("%lu \n", sizeof(s));
/*Why is this working?*/
while (i <= 5)
{
s[i] = 'l';
i++;
}
printf("%s \n", s);
printf("%lu \n", sizeof(char));
printf("%lu \n", sizeof(s[0]));
}
注意: :在我使用的环境中(Windows 7,NI Run-Time,调试等),我都遇到了段错误,这在某种程度上支持其他答案中未定义的行为断言.
Note: In the environment I use, (Windows 7, NI Run-Time, debug, etc) I get a seg-fault either way, which somewhat supports the undefined behavior assertions in other answers.
这篇关于这个malloc不应该工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!