views:

79

answers:

2

I've been getting into some assembly lately and its fun as it challenges everything i have learned. I was wondering if i could ask a few questions

  1. When running an executable, does the entire executable get loaded into memory?

  2. From a bit of fiddling i've found that constants aren't really constants? Is it just a compiler thing?

const int i = 5;

_asm { mov i, 0 } // i is now 0 and compiles fine

So are all variables assigned with a constant value embedded into the file as well? Meaning:

int a = 1;

const int b = 2;

void something() { const int c = 3; int d = 4; }

Will i find all of these variables embedded in the file (in a hex editor or something)?

  1. If the executable is loaded into memory then "constants" are technically using memory? I've read around on the net people saying that constants don't use memory, is this true?
+2  A: 
  1. Your executable's text (i.e. code) and data segments get mapped into the process's virtual address space when the executable starts up, but the bytes might not actually be copied from the disk until those memory locations are accessed. See http://en.wikipedia.org/wiki/Demand_paging

  2. C-language constants actually exist in memory, because you have to be able to take the address of them. (That is, &i.) Constants are usually found in the .rdata segment of your executable image.

  3. A constant is going to take up memory somewhere--if you have the constant number 42 in your program, there must be somewhere in memory where the 42 is stored, even if that means that it's stored as the argument of an immediate-mode instruction.

Will
+1  A: 

The OS loads the code and data segments in order to prepare them for execution.
If the executable has a resource segment, the application loads parts of it at demand.

It's true that const variables take memory space but compilers are free to optimize
for memory usage and code size, and embed their values in the code.
(in case they don't detect any address references for those variables)

const char * aka C strings, usually are interned by the compilers, to save memory.

Nick D