是在栈上还是堆上?
我有一些令人困惑的 C 代码。 由于与此代码有关的原因,我想知道如何判断 struct
对象最终位于堆还是堆栈上?
这些对象是 不是使用 malloc
或 calloc
创建的。 它们以数组的形式开始它们的生命。 出于本文的目的,我将将该结构称为 Emp。
Emp myEmp[6];
/* Each myEmp[?] item is populated in code */
对象以各种方式排序和操作,在某些时候,对象被复制然后传递给数组指针。 复制是通过memcpy完成的。 然后将对象放入类似:Emp* emps_a[6]
中。
这些对象来自副本并分配给上面的 emps_a。
int i;
for( i = 0; i < n; i++ )
{
emps_a[i] = myEmpsCopy + i;
}
我不确定这是否与我的问题有关。 我从不需要 free() 或进行内存清理...恐怕我对 C 不太了解。
非常感谢您的帮助。
I have some C code that is something of a puzzle. For a reason to do with this code, I'm wondering how I can tell if a struct
object is ending up on the heap or stack?
The objects are not being created with malloc
or calloc
. They start their life in the form of an array. For the purposes of this post, I'm going to call the struct Emp.
Emp myEmp[6];
/* Each myEmp[?] item is populated in code */
The objects are sorted and manipulated in various ways and at some point, the objects are copied and then handed to a array-pointer. The copy is done via memcpy
. The objects are then put in to something like: Emp* emps_a[6]
.
The objects go from a copy and are assigned in to the above emps_a.
int i;
for( i = 0; i < n; i++ )
{
emps_a[i] = myEmpsCopy + i;
}
I'm not sure if some or any of this has bearing on my question. I never need free() or do memory clean up... I'm afraid I don't know too much about C.
The help is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除了使用
static
修饰符声明的全局变量和变量(分配在单独的内存区域中)之外,在函数体中声明的局部变量都在堆栈上分配,而无论您调用malloc for 分配在堆上。 此外,C99 可变大小的数组和使用
_alloca
分配的内存最终将位于堆栈上。例如,在上面的代码中,堆栈上有一个
int*
值数组,保存堆中 10 个不同位置的地址。Leaving global variables and variables declared with
static
modifier (which are allocated in a separate memory region) aside, local variables declared in a function body are allocated on the stack whereas whatever you callmalloc
for is allocated on the heap. Also, C99 variable sized arrays and memory allocated with_alloca
will end up on stack.For example, in the above code, there's an array of
int*
values on the stack holding addresses to 10 different locations in the heap.