为什么在C中使用malloc时要指定大小? [英] Why do you specify the size when using malloc in C?

查看:26
本文介绍了为什么在C中使用malloc时要指定大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

取以下代码:

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 常见问题解答的内存分配部分有用的参考咨询.请参阅7.3b.

For questions such as this, the Memory Allocation section of the C FAQ is a useful reference to consult. See 7.3b.

在相关(幽默)笔记中,另请参阅 bloopers 来自 艺术.

On a related (humorous) note, see also a list of bloopers by ART.

这篇关于为什么在C中使用malloc时要指定大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆