堆栈变量与堆变量 [英] Stack variables vs. Heap variables

查看:114
本文介绍了堆栈变量与堆变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在想,正确的:

char *buff[500];

...创建堆栈变量,和

... creates a stack variable, and:

char *buff = (char *)malloc(500);

...创建一个堆变量?

... creates a heap variable?

如果这是正确的,当你为什么会在堆栈变量,反之亦然使用堆变量。我理解堆栈更快还有什么。

If that's correct, when and why would you use heap variables over stack variables and vice versa. I understand the stack is faster is there anything else.

最后一个问题,是主要的功能堆栈上的堆栈帧?

One last question, is the main function a stack frame on the stack?

推荐答案

是的,第一个创建char指针在栈中的一个阵列,约 500 * 4字节和第二个分配在堆500个字符,并指出一个堆栈字符PTR给他们。

Yes, first one creates an array of char pointers in the stack, about 500*4 bytes and second one allocates 500 chars in the heap and points a stack char ptr to them.

在堆栈中分配是方便,快捷,但堆栈是有限的,堆是慢,但更大。除此之外,堆栈分配的值被删除一旦你离开的范围,所以它是像原始变量当地小值非常好。

Allocating in the stack is easy and fast, but stack is limited, heap is slower but much bigger. Apart from that, stack allocated values are "deleted" once you leave the scope, so it is very good for small local values like primitive variables.

如果您分配在堆栈太多,你可能会耗尽堆栈及模具,为你执行的功能在堆栈中的堆栈帧和所有的局部变量的函数都存储在那里,所以打算过深成函数调用可能让你成为一个计算器,以及

If you allocate too much in the stack you might run out of stack and die, main as all the functions you execute has a stack frame in the stack and all the local variables to the function are stored there, so going too deep into function calling might get you into a stackoverflow as well.

在总体上拇指分配任何东西,你在堆中经常使用和大于一百个字节,而小的变量和指针在堆栈中的一个很好的规则。

In general is a good rule of thumb to allocate anything that you use often and is bigger than a hundred bytes in the heap, and small variables and pointers in the stack.

这篇关于堆栈变量与堆变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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