char x[256] vs. char* = malloc(256*sizeof(char)); [英] char x[256] vs. char* = malloc(256*sizeof(char));

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

问题描述

最近有人在我正在使用的一段代码中向我指出

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);

我的印象是这种设置数组的方式与使用

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

char name[256];

而且这两种方式都需要使用 free().我错了,如果有的话,请用低级术语解释一下有什么区别?

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?

推荐答案

在第一个代码中,内存是在堆上动态分配的.该内存需要使用 free() 释放.它的生命周期是任意的:它可以跨越函数边界等

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.

在第二个代码中,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.

附录(Pax):

如果我可以补充一点,Ned,大多数实现通常会提供比堆栈更多的堆(至少在默认情况下).这对于 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(char) 始终为 1,因此您不需要多余的乘法.尽管编译器可能会优化它,但它会使代码变得丑陋,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.

结束附录(Pax).

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

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