【问题标题】:Memory allocation amount to stack and heap (c)堆栈和堆的内存分配量(c)
【发布时间】:2017-01-04 02:10:51
【问题描述】:

我试图了解分配给堆栈和堆的内存量。 假设 sizeof(char) = 1 字节,并且 sizeof(void *) = 4 字节。 给出以下代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
    int i;
    char *str1 = "hello";
    char str2[] = "hello";
    char *str3 = (char*)malloc(strlen(str2));
    //free code
    return 0;
}

我们被告知分配给堆的内存量是 5 个字节,我知道这确实是 malloc 中的数量 (strlen(str2) = 5)。 但是,我不明白分配给堆栈的内存量是 18 字节?我想如果他们给我们一个指针大小为 4 个字节的信息,那么我们有 4 个字节用于指针 str1,另外 6 个字节用于数组 str2(包括“/0”)。我错过了什么?堆栈的 18 个字节来自哪里? 提前感谢您的帮助!

【问题讨论】:

  • istr3 怎么样?

标签: c memory memory-management


【解决方案1】:
int i; // 4 stack bytes
char *str1 = "hello"; // 4 stack bytes (pointing to a read only string constant)
char str2[] = "hello"; // 6 stack bytes (containing a 6 byte string)
char *str3 = (char*)malloc(strlen(str2)); // 4 stack bytes (pointing to heap memory from malloc)

总计:18 个堆栈字节

这是一个理想主义的计算,现实可能更复杂。作为理解记忆的模型,它仍然很有用。

【讨论】:

  • @Vipasane:我扩展了 cmets 以解决您剩下的问题
  • 非常感谢您的努力!你真的帮了我。
猜你喜欢
  • 2011-10-09
  • 2019-05-17
  • 2012-12-05
  • 2011-05-28
  • 2021-11-18
  • 1970-01-01
  • 2018-07-24
  • 1970-01-01
相关资源
最近更新 更多