简体   繁体   English

全局声明是在栈中还是堆中?

[英]global declaration is in stack or heap?

I need to declare a variable that is not in the stack memory but in the heap, like below我需要声明一个不在堆栈内存中但在堆中的变量,如下所示

struct mystruct *name;

Should I declare it outside all functions (even outside main()) at the begin of file?我应该在文件开头的所有函数之外(甚至在 main() 之外)声明它吗?

Please note that a variable is never declared "on the heap".请注意,变量永远不会被声明为“在堆上”。 Only memory pointed to by a pointer can be allocated on (from) the heap.只能在(从)堆上分配指针指向的内存。

In your example, you can declare name indeed outside any function and then it will exist in global memory.在您的示例中,您确实可以在任何函数之外声明name ,然后它将存在于全局内存中。 You can also delcare the variable inside a function, preceded by the keyword static .您还可以在函数内 delcare 变量,前面是关键字static This latter will allocate the variable also in global memory, but it will only be visible in the function where you declared it.后者也会在全局内存中分配变量,但它只会在您声明它的函数中可见。

To use your pointer variable, you now must alocate memory for it to point to, which you allocate on the heap using malloc .要使用您的指针变量,您现在必须为它分配内存以指向它,您可以使用malloc在堆上分配该malloc

TL;DR Version TL;DR 版本

You cannot declare a variable such that the variable itself lives on the heap.你不能声明一个变量,这样变量本身就存在于堆上。

James Michener Version詹姆斯·米切纳版

The C language definition doesn't talk about stacks or heaps; C 语言定义不讨论栈或堆; it talks about storage durations .它谈到了存储持续时间

Objects with auto storage duration (anything declared within a block and without the static keyword) have lifetimes that extend from the beginning of that block and end when the block exits 1 :具有auto存储持续时间的对象(在块内声明且没有static关键字的任何内容)的生命周期从该块的开头开始一直到该块退出时结束1

void foo( void )
{
  int a = 0;                        // lifetime of a extends to the end of
                                    // the function
  for ( int i = 0; i < 10; i++ )    // lifetime of i and b extend to the end
  {                                 // of the for loop
    int b = a + i;    
    printf( "b = %d\n", b );     
  }
}

Most implementations allocate storage for auto objects from the hardware stack, because a stack makes that behavior easy to implement 2 .大多数实现从硬件堆栈为auto对象分配存储空间,因为堆栈使该行为易于实现2

Objects with static storage duration (anything declared outside of a function or with the static keyword) have lifetimes that extend from the time the program is loaded into memory until the program exits:具有static存储持续时间的对象(在函数外部或使用static关键字声明的任何内容)具有从程序加载到内存到程序退出的生命周期:

int a = 0;                   // lifetime of a extends over the lifetime of
                             // the entire program
int main( void )
{
  static int b = 10;         // lifetime of b also extends over the lifetime
                             // of the program, but is only visible within
                             // main
  ...
}

Most implementations will set aside storage for static objects within the body of the executable itself (for an executable using the ELF format, such objects will be stored in the .bss , .data , or .rodata sections of the image).大多数实现会在可执行文件本身的主体中为static对象留出存储空间(对于使用ELF格式的可执行文件,此类对象将存储在映像的.bss.data.rodata部分)。

Objects with allocated storage duration (anything allocated with malloc , calloc , or realloc ) have lifetimes that extend from the time that they are allocated until they are explicitly deallocated with a call to free .具有allocated存储持续时间的对象(使用malloccallocrealloc分配的任何对象)的生命周期从分配它们的时间开始,直到通过调用free显式释放它们为止。

int *foo( size_t size )
{
  int *ptr = malloc( sizeof *ptr * size );  
  return ptr;                               
}

void bar( void )
{
  int *p = foo( 10 );                       
  // do something with p
  free( p );
}

The variables ptr and p only exist for the lifetimes of their respective functions, and they will be typically allocated from the stack.变量ptrp只存在于它们各自函数的生命周期内,它们通常会从堆栈中分配。 The object both variables point to exists from the time it is allocated with malloc until it is deallocated with free .两个变量指向的对象从使用malloc分配时就一直存在,直到使用free解除分配为止。

Most implementations allocate storage for allocated objects from the heap.大多数实现为从堆中allocated对象分配存储。

There's really no way for you to declare an object that has allocated storage duration;你真的没有办法声明一个已经allocated存储期的对象; the only way you can create such an object is via malloc , calloc , or realloc .创建此类对象的唯一方法是通过malloccallocrealloc Whatever object you declare to store the pointer value returned by any of those functions will have either auto or static storage duration.您声明用于存储任何这些函数返回的指针值的任何对象都将具有autostatic存储持续时间。


1. In practice, storage for all local objects is allocated at function entry and released at function exit, regardless of whether the object's lifetime is over the entire function or limited to a block within the function. 1. 实际上,所有本地对象的存储在函数入口分配并在函数退出时释放,无论对象的生命周期是整个函数还是仅限于函数内的一个块。 However, you should never rely on that storage being accessible outside of that object's lifetime. 但是,您永远不应该依赖在该对象的生命周期之外可以访问该存储。 For example, the lifetimes of i and b are limited to the for loop; 例如, ib的生命周期仅限于for循环; even though the storage for each may have been allocated at function entry, you should not attempt to access that storage outside of the loop body. 即使每个的存储可能已经在函数入口分配,您也不应该尝试在循环体之外访问该存储。

2. C was designed on a machine with a stack, after all. 2. 毕竟,C 是在带有堆栈的机器上设计的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM