Where are constant variables stored in C?

CVariablesMemory ManagementConstantsGlobal

C Problem Overview


I wonder where constant variables are stored. Is it in the same memory area as global variables? Or is it on the stack?

C Solutions


Solution 1 - C

How they are stored is an implementation detail (depends on the compiler).

For example, in the GCC compiler, on most machines, read-only variables, constants, and jump tables are placed in the text section.

Solution 2 - C

Depending on the data segmentation that a particular processor follows, we have five segments:

  1. Code Segment - Stores only code, ROM
  2. BSS (or Block Started by Symbol) Data segment - Stores initialised global and static variables
  3. Stack segment - stores all the local variables and other informations regarding function return address etc
  4. Heap segment - all dynamic allocations happens here
  5. Data BSS (or Block Started by Symbol) segment - stores uninitialised global and static variables

Note that the difference between the data and BSS segments is that the former stores initialized global and static variables and the later stores UNinitialised ones.

Now, Why am I talking about the data segmentation when I must be just telling where are the constant variables stored... there's a reason to it...

Every segment has a write protected region where all the constants are stored.

For example:

  • If I have a const int which is local variable, then it is stored in the write protected region of stack segment.
  • If I have a global that is initialised const var, then it is stored in the data segment.
  • If I have an uninitialised const var, then it is stored in the BSS segment...

To summarize, "const" is just a data QUALIFIER, which means that first the compiler has to decide which segment the variable has to be stored and then if the variable is a const, then it qualifies to be stored in the write protected region of that particular segment.

Solution 3 - C

Consider the code:

const int i = 0;
static const int k = 99;

int function(void)
{
    const int j = 37;
    totherfunc(&j);
    totherfunc(&i);
  //totherfunc(&k);
    return(j+3);
}

Generally, i can be stored in the text segment (it's a read-only variable with a fixed value). If it is not in the text segment, it will be stored beside the global variables. Given that it is initialized to zero, it might be in the 'bss' section (where zeroed variables are usually allocated) or in the 'data' section (where initialized variables are usually allocated).

If the compiler is convinced the k is unused (which it could be since it is local to a single file), it might not appear in the object code at all. If the call to totherfunc() that references k was not commented out, then k would have to be allocated an address somewhere - it would likely be in the same segment as i.

The constant (if it is a constant, is it still a variable?) j will most probably appear on the stack of a conventional C implementation. (If you were asking in the comp.std.c news group, someone would mention that the standard doesn't say that automatic variables appear on the stack; fortunately, SO isn't comp.std.c!)

Note that I forced the variables to appear because I passed them by reference - presumably to a function expecting a pointer to a constant integer. If the addresses were never taken, then j and k could be optimized out of the code altogether. To remove i, the compiler would have to know all the source code for the entire program - it is accessible in other translation units (source files), and so cannot as readily be removed. Doubly not if the program indulges in dynamic loading of shared libraries - one of those libraries might rely on that global variable.

(Stylistically - the variables i and j should have longer, more meaningful names; this is only an example!)

Solution 4 - C

Depends on your compiler, your system capabilities, your configuration while compiling.

gcc puts read-only constants on the .text section, unless instructed otherwise.

Solution 5 - C

Usually they are stored in read-only data section (while global variables' section has write permissions). So, trying to modify constant by taking its address may result in access violation aka segfault.

But it depends on your hardware, OS and compiler really.

Solution 6 - C

offcourse not , because

  1. bss segment stored non inilized variables it obviously another type is there.

        (I) large static and global and non constants and non initilaized variables it stored .BSS section.
    
        (II) second thing small static and global variables and non constants and non initilaized variables stored in .SBSS section this included in .BSS segment.
    
  2. data segment is initlaized variables it has 3 types ,

       (I) large static and global and initlaized and non constants variables its stord in .DATA section.
       (II) small static and global and non constant and initilaized variables its stord in .SDATA1 sectiion.
      (III) small static and global and  constant and initilaized OR non initilaized variables its stord in .SDATA2 sectiion.
    

i mention above small and large means depents upon complier for example small means < than 8 bytes and large means > than 8 bytes and equal values.

but my doubt is local constant are where it will stroe??????

Solution 7 - C

This is mostly an educated guess, but I'd say that constants are usually stored in the actual CPU instructions of your compiled program, as immediate data. So in other words, most instructions include space for the address to get data from, but if it's a constant, the space can hold the value itself.

Solution 8 - C

This is specific to Win32 systems.

enter image description here

Solution 9 - C

It's compiler dependence but please aware that it may not be even fully stored. Since the compiler just needs to optimize it and adds the value of it directly into the expression that uses it.

I add this code in a program and compile with gcc for arm cortex m4, check the difference in the memory usage.

Without const:

int someConst[1000] = {0};

enter image description here

With const:

const int someConst[1000] = {0};

enter image description here

Solution 10 - C

Global and constant are two completely separated keywords. You can have one or the other, none or both.

Where your variable, then, is stored in memory depends on the configuration. Read up a bit on the heap and the stack, that will give you some knowledge to ask more (and if I may, better and more specific) questions.

Solution 11 - C

Some constants aren't even stored.

Consider the following code:

int x = foo();
x *= 2;

Chances are that the compiler will turn the multiplication into x = x+x; as that reduces the need to load the number 2 from memory.

Solution 12 - C

It may not be stored at all.

Consider some code like this:

#import<math.h>//import PI
double toRadian(int degree){
  return degree*PI*2/360.0;
}

This enables the programmer to gather the idea of what is going on, but the compiler can optimize away some of that, and most compilers do, by evaluating constant expressions at compile time, which means that the value PI may not be in the resulting program at all.

Solution 13 - C

Just as an an add on ,as you know that its during linking process the memory lay out of the final executable is decided .There is one more section called COMMON at which the common symbols from different input files are placed.This common section actually falls under the .bss section.

Solution 14 - C

I checked on x86_64 GNU/Linux system. By dereferencing the pointer to 'const' variable, the value can be changed. I used objdump. Didn't find 'const' variable in text segment. 'const' variable is stored on stack. 'const' is a compiler directive in "C". The compiler throws error when it comes across a statement changing 'const' variable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser188276View Question on Stackoverflow
Solution 1 - CRobert HarveyView Answer on Stackoverflow
Solution 2 - CwrappermView Answer on Stackoverflow
Solution 3 - CJonathan LefflerView Answer on Stackoverflow
Solution 4 - CMichael FoukarakisView Answer on Stackoverflow
Solution 5 - Celder_georgeView Answer on Stackoverflow
Solution 6 - CmohanView Answer on Stackoverflow
Solution 7 - CLee BView Answer on Stackoverflow
Solution 8 - CharpervilleView Answer on Stackoverflow
Solution 9 - CTrevorView Answer on Stackoverflow
Solution 10 - CMizipzorView Answer on Stackoverflow
Solution 11 - CMSaltersView Answer on Stackoverflow
Solution 12 - CtomjenView Answer on Stackoverflow
Solution 13 - CachooraView Answer on Stackoverflow
Solution 14 - CGangadharView Answer on Stackoverflow