Keerthana
Keerthana

Reputation: 55

Where are structure objects stored in C?

#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;
}

For example in the above program where is the object "stud" stored in memory? Whether it is heap or stack?

Upvotes: 1

Views: 1474

Answers (2)

hanie
hanie

Reputation: 1885

if you declare a variable like stud inside of a function this will be in that function stack.

if this stud is outside of a function (global variable) this will be placed in Uninitialized data segment.

if it was initialized then this would be in Initialized data segment.

only dynamically allocated memory variables will be placed in heap ,so as mentioned in comments this stdu won't be in heap.

static and global variables , if they are initialized ,they will be in Initialized data segment and if they are uninitialized they will be in Uninitialized data segment.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311058

From the C Standard (6.2.4 Storage durations of objects)

1 An object has a storage duration that determines its lifetime. There are four storage durations: static, thread, automatic, and allocated. Allocated storage is described in 7.22.3.

So for example if the object is declared in a function like main

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

    //..
}

then it has the automatic storage duration and will not be alive after exiting the function. You may think that internally the object is created in the stack.

If the object declared outside any function (that is has external or internal linkage) or inside a function with the storage specifier static then it has the static storage duration and will be alive until the program finishes its execution.

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;

    //..
}

The allocated storage duration means when an object is allocated using memory allocation function like malloc. An object with the allocated storage duration is alive until it will be freed using the function free or the program finishes its execution. You may think that internally the object is created in the heap.

An object that is declared with the specifier _Thread_local has thread storage duration. From the same C standard section

Its lifetime is the entire execution of the thread for which it is created, and its stored value is initialized when the thread is started.

Upvotes: 2

Related Questions