是放在堆栈上还是堆上? [英] Is it on the Stack or Heap?

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

问题描述

我有一些令人困惑的C代码.由于使用此代码的原因,我想知道如何确定struct对象是结束在堆还是堆栈上?

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?

创建的对象不是malloccalloc.他们以数组的形式开始他们的生活.出于本文的目的,我将其称为Emp.

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 */

以各种方式对对象进行排序和操作,并在某些时候复制对象,然后将其交给数组指针.复制是通过memcpy完成的.然后将对象放入类似的内容:Emp* emps_a[6].

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].

对象来自副本,并分配给上述emps_a.

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

我不确定这是否与我的问题有关.我永远不需要free()或清理内存...恐怕我对C不太了解.

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.

推荐答案

除了全局变量和使用static修饰符声明的变量(在单独的内存区域中分配),在函数体中声明的局部变量被分配在堆栈,而您调用malloc的任何内容都分配在堆上.同样,C99可变大小的数组和用_alloca分配的内存将最终在堆栈中.

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 call malloc for is allocated on the heap. Also, C99 variable sized arrays and memory allocated with _alloca will end up on stack.

int* x[10];   // The addresses are held on the stack
int i;        // On the stack
for(i = 0; i < 10; ++i)
   x[i] = malloc(sizeof(int)*10);  // Allocates memory on the heap

例如,在上面的代码中,堆栈上有一个int*值数组,用于将地址保存到堆中10个不同的位置.

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.

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

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