如何在堆栈上分配内存并让它指向不同的内存地址以便我以后可以使用它?例如。这段代码:
for (int i = 0; i < 5; i++) {
int nums[5];
nums[0] = 1;
printf("%p\n", &nums[0]);
}
每次都会打印出相同的地址。如何将内存写入堆栈(不是堆,没有 malloc),并且不会覆盖堆栈上的其他内容。
您可以使用alloca
从运行时堆栈中为循环中的每次迭代分配不同的数组。数组内容将保持有效,直到您退出函数:
#include <stdlib.h>
#include <stdio.h>
void function() {
for (int i = 0; i < 5; i++) {
int *nums = alloca(5 * sizeof(*nums));
nums[0] = 1;
printf("%p\n", (void *)nums);
/* store the value of `num` so the array can be used elsewhere.
* the arrays must only be used before `function` returns to its caller.
*/
...
}
/* no need to free the arrays */
}
但是请注意,这alloca()
不是 C 标准的一部分,并且可能不适用于所有架构。关于如何使用它还有进一步的限制,请参阅您系统的文档。
我相信您正在寻找:
一种控制如何在堆栈上分配内存的方法,至少在不覆盖已使用内存的情况下
当然,这是由操作系统处理的!低级系统调用将确保新创建的自动变量不会被写入已使用的内存块。
在您的示例中:
for (int i = 0; i < 5; i++) {
int nums[5];
...
}
情况并非如此,因为当 for 循环的第 i 次迭代终止时,nums
将超出范围。
结果,内存块nums
在第一次迭代期间被存储,在第二次迭代开始时将被标记为空闲,这意味着当nums
第一次迭代将被分配到堆栈中时,它不会知道任何第一次迭代的存在nums
,因为它已经超出了范围 - 它不存在!