是否可以在没有动态内存分配的情况下在 C 函数中初始化结构,使其在函数 returns 之后持续存在?
Is it possible to initialize a struct within a function in C without dynamic memory allocation such that it persists after the function returns?
我目前正在为一个学校项目用 C 语言构建动态内存管理 class。作为堆初始化的一部分,我想将 Block 结构初始化到空闲内存列表中。我不能使用动态内存分配来执行此操作(因为这是违反规则的)。这个设计完全是我自己的创造,所以我的方法可能有缺陷。有可能吗?下面的代码将准确说明我正在尝试做什么。根据我对 C 如何处理变量的理解,一旦函数结束,newBlock 的内存位置就会被抢占,如果它被覆盖,可能会导致以后出现问题。
int mm_init()
{
// Initialize memory. Don't worry about this.
mem_init();
// Initialize the heap.
// Also don't worry about this.
list_init(heap.freeBlocks);
list_init(heap.allocatedBlocks);
// Here is where the question applies.
Block newBlock = //initialize the block.
// freeBlocks is a pointer to a list struct.
list_insert(heap.freeBlocks, &newBlock);
// Don't worry about this either.
return -1;
}
您需要确保变量具有所谓的静态存储持续时间。
静态存储持续时间意味着该对象将在程序启动时与其他具有静态存储持续时间的对象一起一次性分配,并且只要程序存在就永远不会被释放。
有 3 种方法可以为 C 对象指定静态存储持续时间。
使其成为全球性的 -- 这也将使它可以从其他翻译单元访问
Block newBlock;
int mm_init() {
/* ... */
}
使其成为全局并标记它static
-- 这将使标识符只能从当前翻译单元访问
static Block newBlock;
int mm_init() {
/* ... */
}
将其设为本地并标记 static
-- 这将防止标识符在其封闭函数之外可访问
int mm_init() {
static Block newBlock;
/* ... */
}
我目前正在为一个学校项目用 C 语言构建动态内存管理 class。作为堆初始化的一部分,我想将 Block 结构初始化到空闲内存列表中。我不能使用动态内存分配来执行此操作(因为这是违反规则的)。这个设计完全是我自己的创造,所以我的方法可能有缺陷。有可能吗?下面的代码将准确说明我正在尝试做什么。根据我对 C 如何处理变量的理解,一旦函数结束,newBlock 的内存位置就会被抢占,如果它被覆盖,可能会导致以后出现问题。
int mm_init()
{
// Initialize memory. Don't worry about this.
mem_init();
// Initialize the heap.
// Also don't worry about this.
list_init(heap.freeBlocks);
list_init(heap.allocatedBlocks);
// Here is where the question applies.
Block newBlock = //initialize the block.
// freeBlocks is a pointer to a list struct.
list_insert(heap.freeBlocks, &newBlock);
// Don't worry about this either.
return -1;
}
您需要确保变量具有所谓的静态存储持续时间。
静态存储持续时间意味着该对象将在程序启动时与其他具有静态存储持续时间的对象一起一次性分配,并且只要程序存在就永远不会被释放。
有 3 种方法可以为 C 对象指定静态存储持续时间。
使其成为全球性的 -- 这也将使它可以从其他翻译单元访问
Block newBlock; int mm_init() { /* ... */ }
使其成为全局并标记它
static
-- 这将使标识符只能从当前翻译单元访问static Block newBlock; int mm_init() { /* ... */ }
将其设为本地并标记
static
-- 这将防止标识符在其封闭函数之外可访问int mm_init() { static Block newBlock; /* ... */ }