0

Consider the next loop

for(int i = 0; i < 99999999; i++)
{
    double d1 = (double)i/10;
    double d2 = (double)i/100;

    std::cout << d1 * d2 << std::endl;
}

From what I know, the application will allocate and free 16 bytes of memory on the stack (double is 8 bytes on my machine) for every iteration in the loop. Is this true, or are the compilers smart enough to know to free the memory only when the loop ends?

The thing is that variable declaration inside the loop makes the code more readable (imo).

McLovin
  • 3,295
  • 7
  • 32
  • 67
  • 1
    I guess it's smart enough. – Maroun May 10 '15 at 14:05
  • 3
    You realise that "allocating" memory on the stack is simply moving the CPU's stack pointer, right? But yes, the compiler almost certainly performs a single stack adjustment for the entire thing, rather than per iteration. Check the assembler output to be sure. – Oliver Charlesworth May 10 '15 at 14:06
  • You can add static. That will guarantee they will be allocated once. – Benjy Kessler May 10 '15 at 14:06
  • @BenjyKessler: You really don't want `static` here. – Oliver Charlesworth May 10 '15 at 14:07
  • @OliverCharlesworth Nope, what's the stack pointer? My knowledge comes from some books that did not cover this subject – McLovin May 10 '15 at 14:07
  • @Pilpel For simple local variables (ie. not the ones allocated by new/malloc, ie. only things the compiler knows already when compiling), there is a reserved memory part with simplified memory management (="stack"), where it isn´t known where something is allocated and how big it is, only "where is the first free space" as one address number. How the not.free part is used is managed by the compiler. And to reserve space on the stack, only the first-free-address needs to be modified. A bit more info: http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap – deviantfan May 10 '15 at 14:15

1 Answers1

3

Stack allocation is nothing more than increasing and decreasing the value of a register.

Even if the compiler is a dumb one this means executing at most 1 ADD and 1 SUB instruction for each iteration. This is unlikely in any case, since the compiler knows that they are locals to the loop and that they can't change their size.

Actually they could also not stay on stack at all, since they could be fit in two floating point registers for the whole loop.

Jack
  • 131,802
  • 30
  • 241
  • 343