malloc和realloc的区别? [英] Difference between malloc and realloc?

查看:121
本文介绍了malloc和realloc的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经创建10个元素的整数阵列中两个code样本:

Suppose I've two code samples for creating a integer array of 10 elements:

int *pi = (int*) 0xDEADBEEF; 
realloc(pi,10);

和另一个是正常写入所述一个,即:

and the other is the one that is written normally, i.e.:

int *pi;
pi= malloc(10*sizeof(int));

现在,我的问题是:第一类的分配是合法的,但没有使用。为什么呢,虽然我可能会得到我的选择的起始位置?
与常量指针Iniitialization是合法的,但没有使用。为什么呢?

Now, my question is: The first type of assignment is legal but not used. Why, although there I may get the starting location of my choice? Iniitialization of pointers with constants are legal but not used. Why?

推荐答案

哈啊,不!这第一个电话是不合法的。你可以不通过的realloc 最佳一些随机指针和希望。以realloc的第一个参数,必须为指向内存的指针,你的程序是pviously分配(通过类似的malloc 释放calloc 或朋友),或一个空指针。

Ahhhh, no! That first call is not legal. You can't pass realloc some random pointer and hope for the best. The first parameter to realloc has to be either a pointer to memory that your program was previously allocated (through something like malloc, calloc or friends) or a null pointer.

在传递 NULL ,它等同于的malloc 。如果你再在某种循环分配和不希望有一个特殊的情况下,第一次分配的NULL调用可能是有用的。

When NULL is passed, it's equivalent to malloc. The NULL call can be useful if you're re allocating in some kind of loop and don't want to have a special case the first time you allocate.

虽然我们在这,要使用malloc和realloc的相当标准的方法是:

While we're at it, the fairly standard ways to use malloc and realloc are:

int* p;
p = malloc(10 * sizeof(int)); //Note that there's no cast
//(also, it could just be int* p = malloc(...);)

int* np = realloc(p, 15 * sizeof(int));
//Note that you keep the old pointer -- this is in case the realloc fails


为切旁白:历史是你看到在不同线路上的声明和任务的主要原因。在老版本的C,声明必须是第一位的函数。这意味着,即使你的函数没有使用变量,直到20行,你必须在顶部声明。


As a tangential aside: history is the main reason you see declarations and assignments on different lines. In older versions of C, declarations had to come first in functions. That meant that even if your function didn't use a variable until 20 lines in, you had to declare at the top.

既然你通常不知道不能用于其它20行的变量的值应该是什么,你不能总是初始化为有意义的事情,因此你留下了一个声明,并在没有转让你的函数的顶部。

Since you typically don't know what the value of a variable not used for another 20 lines should be, you can't always initialize it to anything meaningful, and thus you're left with a declaration and no assignment at the top of your function.

在C99 / C11,你不必在范围的顶部声明变量。事实上,它的一般建议定义变量接近它们作为可能使用

In C99/C11, you do not have to declare variables at the top of scopes. In fact, it's generally suggested to define variables as close to their use as possible.

这篇关于malloc和realloc的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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