A simple C ++ question about memory usage

What is the difference (reasonable memory) bewteen:

for(int x=0;x<100;x++)
{
  int y = 1+x;
}
and


int y = 0;
for(int x=0;x<100;x++)
{
  y = 1+x;
}

I always wondered if they are the same or the first is a waste of memory? ...

+3
source share
6 answers

Memory, no difference. y is on the stack where it is declared in the method. Here the only difference is the scope of y: in the second case, it is limited by the body of the for loop; firstly, it is not. This is purely at the language level: again, y is distributed exactly the same, that is, on the stack.

Just to make this point perfectly clear, here is a sample code:

void method1() {
    for (;;) {
        int a = 10;
    }
}

void method2() {
    int a;
    for (;;) {
        a = 10;
    }
}

Here is the assembler generated in debug mode in both cases:

# method1() 
00000000  push        ebp  
00000001  mov         ebp,esp 
00000003  push        eax  
00000004  cmp         dword ptr ds:[00662E14h],0 
0000000b  je          00000012 
0000000d  call        5D9FE081 
00000012  xor         edx,edx 
00000014  mov         dword ptr [ebp-4],edx 
00000017  mov         dword ptr [ebp-4],0Ah 
0000001e  nop              
0000001f  jmp         00000017 

# method2() 
00000000  push        ebp  
00000001  mov         ebp,esp 
00000003  push        eax  
00000004  cmp         dword ptr ds:[002B2E14h],0 
0000000b  je          00000012 
0000000d  call        5ED1E089 
00000012  xor         edx,edx 
00000014  mov         dword ptr [ebp-4],edx 
00000017  mov         dword ptr [ebp-4],0Ah 
0000001e  nop              
0000001f  jmp         00000017 

, , . , , a, .

, , , , std::vector: , , , , , . :

for (/* index */) {
    std::vector<int> a; // invokes the constructor of std::vector<int> everytime
} // destructor called each time the object goes out of scope

std::vector<int> a; // constructor only called once
for (/* index */) {

}

, : -:

for (/* index */) {
    char *a = new char[100]; // allocates 100 additional bytes every time !
} // must remember to delete[] a in the loop, otherwise it a memory leak !

//////

char *a = new char[100]; // only one allocation
for (/* index */) {

}
+20

- sizeof(int) bytes; y , - . (, }, -).

+6

- , , - , .

+1

. ( ) 2- . , , y ( ) , "" , , . :)

+1

, .

, (sizeof (int) ), , , .

, , ; , //.

0

:

for(int x=0;x<100;x++)
{
  int y = 1+x;
}
z = y-3; // <=== ERROR!

y for.

int y = 0;
for(int x=0;x<100;x++)
{
  y = 1+x;
}
z = y-3; // <=== OK

y .

0

Source: https://habr.com/ru/post/1715489/


All Articles