gpt4 book ai didi

c - 一个程序为静态对象、自动对象和动态分配的对象使用不同的内存区域

转载 作者:太空狗 更新时间:2023-10-29 16:33:35 25 4
gpt4 key购买 nike

我正在阅读“C Primer Plus”这本书,遇到了理解内存区域的问题。书中写道:

Typically, a program uses different regions of memory for static objects, automatic objects, and dynamically allocated objects. Listing 12.15 illustrates this point.

// where.c -- where's the memory?

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

int static_store = 30;
const char * pcg = "String Literal";
int main(void)
{
int auto_store = 40;
char auto_string[] = "Auto char Array";
int *pi;
char *pcl;

pi = (int *) malloc(sizeof(int));
*pi = 35;
pcl = (char *) malloc(strlen("Dynamic String") + 1);
strcpy(pcl, "Dynamic String");

printf("static_store: %d at %p\n", static_store, &static_store);
printf(" auto_store: %d at %p\n", auto_store, &auto_store);
printf(" *pi: %d at %p\n", *pi, pi);
printf(" %s at %p\n", pcg, pcg);
printf(" %s at %p\n", auto_string, auto_string);
printf(" %s at %p\n", pcl, pcl);
printf(" %s at %p\n", "Quoted String", "Quoted String");
free(pi);
free(pcl);

return 0;
}

运行代码得到:

static_store: 30 at 0x10a621040
auto_store: 40 at 0x7ffee55df768
*pi: 35 at 0x7fbf1d402ac0
String Literal at 0x10a620f00
Auto char Array at 0x7ffee55df770
Dynamic String at 0x7fbf1d402ad0
Quoted String at 0x10a620f9b

本书的结论:

As you can see, static data, including string literals occupies one region, automatic data a second region, and dynamically allocated data a third region (often called a memory heap or free store).

我可以弄清楚它们的地址不同。我怎么能保证他们是不同地区的呢?

最佳答案

不同的地区有非常不同的地址。如果他们在同一个地区,他们就会有相似的地址。更好的例子,我们在每个区域分配 2 个对象:

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

int main (void)
{
int stack1;
int stack2;
static int bss1;
static int bss2;
static int data1=1;
static int data2=1;
int* heap1 = malloc(1);
int* heap2 = malloc(1);
char* rodata1 = "hello";
char* rodata2 = "world";

printf(".stack\t%p %p\n", &stack1, &stack2);
printf(".bss\t%p %p\n", &bss1, &bss2);
printf(".data\t%p %p\n", &data1, &data2);
printf(".heap\t%p %p\n", heap1, heap2);
printf(".rodata\t%p %p\n", rodata1, rodata2);

free(heap1);
free(heap2);
}

输出(例如):

.stack  000000000022FE2C 000000000022FE28
.bss 0000000000407030 0000000000407034
.data 0000000000403010 0000000000403014
.heap 0000000000477C50 0000000000477C70
.rodata 0000000000404000 0000000000404006

如您所见,同一段中的两个变量具有几乎相同的地址,唯一的区别是对象的大小(可能还有一些对齐空间)。虽然与其他段中的变量相比,它们的地址非常不同。

关于c - 一个程序为静态对象、自动对象和动态分配的对象使用不同的内存区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52855674/

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