静态,堆栈和堆分配有何不同?

时间:2012-11-16 15:42:37

标签: c arrays static stack

我如何声明这样的数组:

int array[1000000];

作为静态数组,堆栈数组和堆分配数组?

4 个答案:

答案 0 :(得分:2)

您的作业似乎在寻找:

// global variable; NOT on the stack. Exists in the data segment of the program
int globalvar[1000000];

void func()
{
    // local stack-variable. allocated on the stack on function entry
    //  unavailable outside this function scope.
    int stackvar[1000000];

    // allocated on the heap. the only stack space used in the
    //  space occupied by the pointer variable.
    int *heapvar = malloc(1000000 * sizeof(int));
    if (heapvar != NULL)
    {
        // use heap var

        // free heap var
        free(heapvar)
    }
}

或许这个:

void func()
{
    // static variable; NOT on the stack. Exists in a program data segment (usually)
    static int staticvar[1000000];
    
    // local stack-variable. allocated on the stack on function entry
    //  unavailable outside this function scope.
    int stackvar[1000000];

    // allocated on the heap. the only stack space used in the
    //  space occupied by the pointer variable.
    int *heapvar = malloc(1000000 * sizeof(int));
    if (heapvar != NULL)
    {
        // use heap var

        // free heap var
        free(heapvar)
    }
}

对于它的价值,除非你有一个4或8兆字节的预留调用堆栈(或更大),否则上面的函数可能会在输入时出现问题。对于如此大的尺寸,通常使用堆(malloc() / free())。但这不是你的任务似乎(还)。

答案 1 :(得分:0)

函数内部的静态声明意味着声明的变量在声明它的函数的执行之间共享。堆栈是内存中的一个位置,可以被现在运行的任何函数使用;当你的功能没有运行时,没有办法保护堆栈上的某个区域不被覆盖。静态变量通常存储在数据中,或者如果整合到程序的bss部分中。如果你有严格的要求让数组在堆栈中,你可以尝试复制它:

void foo(void) {
   static int my_static_array[16];
   int array_copy[16];

   memcpy(array_copy,my_static_array,sizeof array_copy);

   /* do funny stuff */

   memcpy(my_static_array,array_copy,sizeof my_static_array);
}

答案 2 :(得分:0)

静态变量不能在堆栈上,这是因为静态和局部变量根本不同,局部变量“生活”在堆栈中,而静态变量“生活”在静态段中。如果希望局部变量对于声明局部变量的函数调用的函数可见,则应将该局部变量作为参数传递。 另一个解决方案不推荐是有一个指向数组的静态指针,并指向堆栈中存在的数组,只要声明本地数组的函数,它就会有效。没有回来。返回后,指针将指向可能存在其他数据的区域,这意味着可以覆盖返回地址或不相关的局部变量或函数参数。

答案 3 :(得分:0)

如果你想让它array公开,你可以在任何范围之外(代码块之外)定义它,它将在二进制文本段中声明。