堆栈和堆中的内存分配 [英] memory allocation in Stack and Heap

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

问题描述

这似乎是一个非常基本的问题,但它一直困扰着我,

This may seem like a very basic question, but its been in my head so:

当我们分配局部变量时,它将进入堆栈.类似地,动态分配会使变量继续在堆上.现在,我的问题是,这个变量是实际位于堆栈还是堆上,或者我们只是堆栈和堆中的引用.

When we allocate a local variable, it goes into stack. Similarly dynamic allocation cause the variable to go on heap. Now, my question is, is this variable actually lie on stack or heap or we will just a reference in the stack and Heap.

例如,

假设我声明了一个变量int i.现在,此i已分配在堆栈上.因此,当我打印i的地址时,这将是堆栈上的位置之一吗?堆也有同样的问题.

Suppose I declare a variable int i. Now this i is allocated on the stack. So, when I print the address of i, this will be one of the location on stack? Same question for heap as well.

推荐答案

我不确定您要问什么,但我会尽力回答.

I'm not entirely sure what you're asking, but I'll try my best to answer.

以下内容在堆栈上声明了变量i:

The following declares a variable i on the stack:

int i;

当我使用&i询问地址时,便获得了堆栈中的实际位置.

When I ask for an address using &i I get the actual location on the stack.

当我使用malloc动态分配内容时,实际上存储了 两个 数据.动态内存分配在堆上,而指针本身分配在堆栈上.所以在这段代码中:

When I allocate something dynamically using malloc, there are actually TWO pieces of data being stored. The dynamic memory is allocated on the heap, and the pointer itself is allocated on the stack. So in this code:

int* j = malloc(sizeof(int));

这是在堆上分配一个整数空间.它还在堆栈上为指针(j)分配空间.变量j的值设置为malloc返回的地址.

This is allocating space on the heap for an integer. It's also allocating space on the stack for a pointer (j). The variable j's value is set to the address returned by malloc.

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

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