【问题标题】:Where are structure objects stored in C?结构对象在 C 中存储在哪里?
【发布时间】:2020-07-14 13:58:03
【问题描述】:
#include<stdio.h>

struct student_college_detail
{
 int college_id;
 char college_name[50];
}stud;


int main() 
{
    struct student_college_detail stud= {71145,"Anna University"};
    printf(" College Id is: %d \n",stud.college_id);
    printf(" College Name is: %s \n",stud.college_name);
    return 0;
}

例如在上面的程序中,对象 "stud" 存储在内存中的什么位置?是堆还是栈?

【问题讨论】:

  • 定义出现在函数内部还是外部?
  • @Keerthana 您没有显示此声明发生的位置..
  • 我们只能说它不是堆分配的变量,只是动态分配的内存来自“堆”。否则,它取决于您定义结构对象的 where。请edit您的问题包括minimal reproducible example
  • 无处可去。在这里你只是定义它而不是实例化它。
  • @Ra'Jiska 如果在struct 之前有一个typedef 然后stud 将是类型,那么@Ra'Jiska 将是正确的,但这里studstruct student_college_detail 的一个实例。

标签: c memory memory-management structure heap-memory


【解决方案1】:

如果您在函数内部声明像 stud 这样的变量,它将在该函数堆栈中。

如果此 stud 位于函数(全局变量)之外,则它将被放置在 Uninitialized data segment 中。

如果它被初始化,那么这将在Initialized data segment

只有动态分配的内存变量会放在heap 中,所以正如cmets 中提到的,这个stdu 不会在heap 中。

staticglobal 变量,如果它们被初始化,它们将在Initialized data segment,如果它们未初始化,它们将在 Uninitialized data segment.

【讨论】:

    【解决方案2】:

    来自 C 标准(6.2.4 对象的存储持续时间)

    1 对象具有决定其生命周期的存储持续时间。那里 有四个存储持续时间:静态、线程、自动和分配。 分配的存储在 7.22.3.

    例如,如果对象在 main 之类的函数中声明

    int main( void )
    {
        struct student_college_detail
        {
            int college_id;
            char college_name[50];
        } stud;
    
        //..
    }
    

    则具有自动存储时长,退出该功能后将不再存活。你可能认为内部对象是在堆栈中创建的。

    如果在任何函数外部(即具有外部或内部链接)或在具有存储说明符 static 的函数内部声明的对象,则它具有静态存储持续时间,并且在程序完成执行之前将处于活动状态。

    struct student_college_detail
    {
        int college_id;
        char college_name[50];
    } stud;
    
    int main( void )
    {
        static struct student_college_detail
        {
            int college_id;
            char college_name[50];
        } stud;
    
        //..
    }
    

    分配的存储持续时间是指使用malloc等内存分配函数分配对象的时间。具有分配存储持续时间的对象是活动的,直到使用函数 free 将其释放或程序完成执行。你可能会认为内部对象是在堆中创建的。

    使用说明符_Thread_local 声明的对象具有线程存储持续时间。来自同一个 C 标准部分

    它的生命周期是它所在线程的整个执行过程 创建,并且它的存储值在线程被初始化时被初始化 开始了。

    【讨论】:

      猜你喜欢
      • 2021-08-17
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 2012-02-24
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      相关资源
      最近更新 更多