C中的数组实例化 - 栈或堆分配? [英] C Array Instantiation - Stack or Heap Allocation?

查看:282
本文介绍了C中的数组实例化 - 栈或堆分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我保证,这个问题已经被问过,但我一直无法通过搜索找到它;提前进行裁员的遗憾。

这是我的(可能是错误的)的理解是,你只分配到堆栈当你知道一个对象在编译时的大小。因此,在初始化数组的情况下,你可以做其中之一(这应该在栈上):

 字符charArray [50];

由于该数组的大小是在编译时已知,这应该没有问题。

在另一方面,这(我相信)也是有效的code:

 字符anotherCharArray [someVariable + 50];

这会进入堆叠呢?我是pretty确保code段错误,如果你免费()这一点,所以这让我想到这样做,但它并没有真正意义的我。同样地,在这里你必须使用free()的时候数据是通过分配的malloc?100%的唯一情况

在此先感谢您的帮助。


解决方案

  

同样,在这里你必须使用free()的时候数据是通过分配的malloc?100%的唯一情况


是的。 (除了释放calloc和realloc,其返回值也为免费()'D。同样,也有使用malloc()函数,这一事实被记录,为例如的strdup() - 这些函数的返回值也是使用被释放免费(),很明显)

 字符anotherCharArray [someVariable + 50];


  

这会进入堆叠呢?


是的,它(在大多数实现 - 当然,这不是的总是的事实,你承担,但在大多数的平台,它是)。是的,这是有效的code,但它只是在C99标准。

I guarantee that this question has been asked before, but I haven't been able to find it via search; sorry in advance for any redundancies.

It's my (potentially wrong) understanding that you only allocate to the stack when you know the size of an object at compile time. So in the case of initializing an array, you could do one of these (and this should go on the stack):

char charArray[50];

Since the size of this array is known at compile time, this should have no issues.

On the other hand, this (I believe) is also valid code:

char anotherCharArray[someVariable + 50];

Would this go on the stack as well? I am pretty sure the code segfaults if you free() this, so it makes me think it does, but it doesn't really make sense to me. Similarly, is the 100% sole situation where you have to use free() when the data was allocated via malloc?

Thanks in advance for your help.

解决方案

Similarly, is the 100% sole situation where you have to use free() when the data was allocated via malloc?

Yes. (Apart from calloc and realloc, their return value is also to be free()'d. Similarly, there are functions that use malloc() and this fact is documented, for example strdup() - the return value of these functions is also to be freed using free(), obviously.)

char anotherCharArray[someVariable + 50];

Would this go on the stack as well?

Yes, it does (in most implementations - of course, it's not always true that you assume, but on most of the platforms, it is). And yes this is valid code, but it is only standard in C99.

这篇关于C中的数组实例化 - 栈或堆分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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