焦X [256]对字符* =的malloc(256 * sizeof的(炭)); [英] char x[256] vs. char* = malloc(256*sizeof(char));

查看:119
本文介绍了焦X [256]对字符* =的malloc(256 * sizeof的(炭));的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里最近有人向我指出在一块,我用我的code

Someone here recently pointed out to me in a piece of code of mine I am using

char* name = malloc(256*sizeof(char));
// more code
free(name);

我是IM pression下,设立一个数组的这种方式是相同的使用

I was under the impression that this way of setting up an array was identical to using

char name[256];

和,这两个途径将需要使用的游离()。我错了,如果是这样可能有人请在较低水平来解释的区别是什么?

and that both ways would require the use of free(). Am I wrong and if so could someone please explain in low level terms what the difference is?

推荐答案

在第一code,内存动态分配在堆上。内存需要与自由释放()。它的寿命是任意的:它可以跨越函数边界等

In the first code, the memory is dynamically allocated on the heap. That memory needs to be freed with free(). Its lifetime is arbitrary: it can cross function boundaries, etc.

在第二code时,256个字节被分配在栈上,并在函数返回时(或在程序终止,如果它是外部的所有功能)是自动回收。所以,你不必(也不能)就可以调用free()。它不能漏气,但它也不会活超越函数的末尾。

In the second code, the 256 bytes are allocated on the stack, and are automatically reclaimed when the function returns (or at program termination if it is outside all functions). So you don't have to (and cannot) call free() on it. It can't leak, but it also won't live beyond the end of the function.

两个基于所述存储器的要求之间进行选择。

Choose between the two based on the requirements for the memory.

附录(大同):

如果我可以添加到这个斯内德,大多数实现通常会提供更多的堆比栈(至少是默认)。这通常不会对无关紧要256个字节,除非你已经用完堆栈或做大量递归的东西。

If I may add to this, Ned, most implementations will typically provide more heap than stack (at least by default). This won't typically matter for 256 bytes unless you're already running out of stack or doing heavily recursive stuff.

此外,sizeof的(炭)始终是1,根据标准,所以你并不需要一个多余的繁衍。即使编译器可能会优化它走,它使code丑陋IMNSHO。

Also, sizeof(char) is always 1 according to the standard so you don't need that superfluous multiply. Even though the compiler will probably optimize it away, it makes the code ugly IMNSHO.

末增编(人)。

这篇关于焦X [256]对字符* =的malloc(256 * sizeof的(炭));的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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