Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does structure declaration occupies memory?

struct books
{
    char name[100];
    float price;
    int pages;
};

Declaring a structure Without creating an object of a structure, does the structure occupies space in memory for its DATA MEMBERS?

like image 361
kevin gomes Avatar asked Feb 05 '14 17:02

kevin gomes


3 Answers

The definition of a struct is normally not part of the binary in C. It only exists in your source code.

When the compiler sees references to your struct (typically for allocation or deallocation of space for an instance of this struct, access to its fields through an object variable, etc), it consults your struct definition in order to understand what the correct numbers are for that data type (it mainly wants to calculate data type sizes and field offsets).

When all this is done, the struct definition itself is forgotten and only the numbers are kept in the program, wherever they were actually used.

Therefore, if you don't reference your struct at all, then no traces of it should be present.

like image 139
Theodoros Chatzigiannakis Avatar answered Oct 02 '22 17:10

Theodoros Chatzigiannakis


Does structure declaration occupies memory?

No - you won't consume memory until you declare a variable on the stack, heap, or shared memory. You're simply defining a new data type that consists of more than one other data type.

This would consume memory:

const struct books myBooks = { ...initialization code... }; \\ Consuming CODE memory (typically ROM)

struct books myBooks = { ...initialization code... }; \\ Consuming DATA memory (typically RAM)

like image 37
bblincoe Avatar answered Oct 02 '22 17:10

bblincoe


No. In a compiled program type declarations/definitions exist only as compile-time concepts. They leave no trace in the compiled code and do not affect run-time memory consumption. Storage in C program is occupied by objects. Types are not objects.

like image 43
AnT Avatar answered Oct 02 '22 15:10

AnT