为什么用C使用malloc当您指定的大小? [英] Why do you specify the size when using malloc in C?
问题描述
看看下面code:
int *p = malloc(2 * sizeof *p);
p[0] = 10; //Using the two spaces I
p[1] = 20; //allocated with malloc before.
p[2] = 30; //Using another space that I didn't allocate for.
printf("%d", *(p+1)); //Correctly prints 20
printf("%d", *(p+2)); //Also, correctly prints 30
//although I didn't allocate space for it
通过行的malloc(2 * sizeof的* P)
我的两个整数分配空间,对吧?但是,如果我添加一个 INT
来第三的位置,我仍然得到正确和检索分配。
With the line malloc(2 * sizeof *p)
I am allocating space for two integers, right ? But if I add an int
to the third position, I still gets allocated correctly and retrievable.
所以我的问题是,当你使用你为什么要指定一个尺寸的malloc
?
So my question is, why do you specify a size when you use malloc
?
推荐答案
简单的逻辑:如果你不合法的停车位停放,没有什么会发生,但有时你的车可能会被拖走,你可能会被套牢了巨额的罚款。而且,有时候,当你试图找到自己的方式到你的车被拖到了一斤,你可能会被卡车碾过。
Simple logic: If you do not park in a legal parking space, nothing might happen but occasionally your car might get towed and you might get stuck with a huge fine. And, sometimes, as you try to find your way to the pound where your car was towed, you might get run over by a truck.
的malloc
给你,你问,许多法律停车位。您可以尝试到别处停放,它似乎工作,但有时不会。
malloc
gives you as many legal parking spots as you asked. You can try to park elsewhere, it might seem to work, but sometimes it won't.
有关问题,如本中,C FAQ 的内存分配部分是一个有益的参考咨询。请参见 7.3B 。
For questions such as this, the Memory Allocation section of the C FAQ is a useful reference to consult. See 7.3b.
On a related (humorous) note, see also a list of bloopers by ART.
这篇关于为什么用C使用malloc当您指定的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!