堆栈和堆上的内存位置模式 [英] memory location patterns on stack and heap

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

问题描述

我只是想知道堆栈和堆上的变量(指针)的地址长度是否相关.在很多情况下,我已经看到,与堆变量相比,与堆栈变量有关的变量通常更长.例如,考虑以下简单测试:

I'm just curious if there is any correlation between the length of the address of a variable (pointer) on stack and heap. On many occasions I have seen that those regarding stack variables are usually longer when compared to heap. For example consider the following simple test:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int i = 0;
    int *j = malloc(sizeof(int)); *j = 0;

    printf("&i = %p\n j = %p\n", &i, j);

    free(j);
    return 0;
}

输出:

&i = 0x7fffe9c7fa5c
 j = 0x100e010

这些结果是在Linux中使用gcc获得的;这可能取决于操作系统/编译器吗?

These results are obtained in linux using gcc; could this be OS/compiler dependent?

推荐答案

结果取决于程序地址空间中堆和堆栈的位置.这些由链接器和处理器体系结构确定.

The results depend on positions of the heap(s) and stack(s) in the address space of the program. These are determined by linker and processor architecture.

由于 ASLR ,确切的数字在现代系统上应该是随机的.

Due to ASLR, the exact numbers should be random on modern systems.

尽管如此,堆通常会向上增长,而向下堆叠.此外,出于性能和内存管理的原因,堆和堆栈都将始终在页面上开始边界.

Nevertheless, heaps will usually grow upwards, and stacks downwards. Additionally, for performance and memory management reasons, both heaps and stacks will always start on page boundaries.

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

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