c++ - 不同类别的内存

标签 c++ memory stack

static const int MAX_SIZE = 256; //I assume this is static Data

bool initialiseArray(int* arrayParam, int sizeParam) //where does this lie?
{ 
 if(size > MAX_SIZE) 
 { 
 return false; 
 } 

 for(int i=0; i<sizeParam; i++) 
 { 
 arrayParam[i] = 9; 
 } 

 return true; 
} 

void main() 
{ 
 int* myArray = new int[30]; //I assume this is allocated on heap memory
 bool res = initialiseArray(myArray, 30); //Where does this lie?
 delete myArray; 
}

我们目前正在学习不同类别的内存,我知道有 -代码内存 -静态数据 -运行时堆栈 -自由存储(堆)

我已经评论了我不确定的地方,只是想知道是否有人可以帮助我。我对运行时堆栈的定义描述了它用于函数,但我的代码内存定义它包含方法/函数的所有指令,所以我有点困惑。

谁能伸出援手?

最佳答案

static const int MAX_SIZE = 256; //I assume this is static Data

的确如此。事实上,因为它是 const ,这个值可能根本不会保留在您的最终可执行文件中,因为编译器可以在它看到 MAX_SIZE 的任何地方替换“256” .

bool initialiseArray(int* arrayParam, int sizeParam) //where does this lie?

initialiseArray() 的代码函数将在您的可执行文件的数据部分中。您可以获得指向内存地址的指针,并通过该地址调用该函数,但除此之外,您无能为力。

arrayParamsizeParam参数将在堆栈上按值传递给函数。同样,bool返回值将被放入调用函数的堆栈区。

int* myArray = new int[30]; //I assume this is allocated on heap memory

正确。

 bool res = initialiseArray(myArray, 30); //Where does this lie?

实际上,myArray指针和文字 30被复制到initialiseArray()的栈区,然后对它们进行操作,然后是结果 bool被复制到调用函数的栈区。

参数传递的实际细节要复杂得多,并且取决于调用约定(其中有几个,特别是在 Windows 上),但除非你正在做一些非常专业的事情,否则它们并不重要 :-)

关于c++ - 不同类别的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20542489/

相关文章:

c++ - C/C++ 中结构的字段对齐

c++ - 冗余静态数据

memory - 在 Rust 中的 mem::replace

java - Activity onDestroy 在 OutOfMemoryError 之前从未被调用过

c - C中的堆栈抽象数据类型

c++ - C++中的引用和常量混淆

c++ - 在 C++ 中将对象转换为 vector

javascript - Node.js 性能和内存泄漏

c - LLDB会改变C程序的环境变量地址吗?

c - C 语言中的一堆单词(回文句)