gpt4 book ai didi

c - 堆栈段中意外的内存分配

转载 作者:行者123 更新时间:2023-11-30 20:01:14 24 4
gpt4 key购买 nike

我试图看到对于给定的函数,内存堆栈段上的内存分配将以连续的方式发生。因此,我编写了以下代码并得到了以下输出。

对于int分配 我看到内存地址按预期出现,但不是字符数组。内存地址0xbff1599c之后我期待下一个地址是 0xbff159a0而不是0xbff159a3 。另外,从char开始是 1 个字节,而我使用的是 4 个字节,所以在 0xbff159a3 之后我在期待0xbff159a7而不是0xbff159a8

如果我删除字符部分,所有内存位置都会按预期出现,但我无法使用字符数组获取预期的内存位置。

我的基本假设是,在堆栈段上,内存始终是连续的。我希望这没有错。

#include <stdio.h>

int main(void)
{
int x = 10;
printf("Value of x is %d\n", x);
printf("Address of x is %p\n", &x);
printf("Dereferencing address of x gives %d\n", *(&x));
printf("\n");

int y = 20;
printf("Value of y is %d\n", y);
printf("Address of y is %p\n", &y);
printf("Dereferencing address of y gives %d\n", *(&y));
printf("\n");

char str[] = "abcd";
printf("Value of str is %s\n", str);
printf("Address of str is %p\n", &str);
printf("Dereferencing address of str gives %s\n", *(&str));
printf("\n");

int z = 30;
printf("Value of z is %d\n", z);
printf("Address of z is %p\n", &z);
printf("Dereferencing address of z gives %d\n", *(&z));
}

输出:

Value of x is 10
Address of x is 0xbff159ac
Dereferencing address of x gives 10

Value of y is 20
Address of y is 0xbff159a8
Dereferencing address of y gives 20

Value of str is abcd
Address of str is 0xbff159a3
Dereferencing address of str gives abcd

Value of z is 30
Address of z is 0xbff1599c
Dereferencing address of z gives 30

最佳答案

Also, since char is 1 byte and I am using 4 bytes, so after 0xbff159a3 I was expecting 0xbff159a7 and not 0xbff159a8

char 占用 1 个字节,但 str 是字符串,您没有计算 '\0'它位于字符串的末尾,因此,char str[]="abcd" 占用 5 字节。

关于c - 堆栈段中意外的内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35115000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com