首页 > 解决方案 > 在堆栈上声明内存会覆盖之前声明的内存

问题描述

如何在堆栈上分配内存并让它指向不同的内存地址以便我以后可以使用它?例如。这段代码:

for (int i = 0; i < 5; i++) {
    int nums[5];
    nums[0] = 1;
    printf("%p\n", &nums[0]);
}

每次都会打印出相同的地址。如何将内存写入堆栈(不是堆,没有 malloc),并且不会覆盖堆栈上的其他内容。

标签: cstackalloca

解决方案


您可以使用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 标准的一部分,并且可能不适用于所有架构。关于如何使用它还有进一步的限制,请参阅您系统的文档。


推荐阅读