C ++ how to free memory correctly?

int main(){
    int *a = new int[5];
    int *b = new int[10];
    int *c;
    for (int i = 0; i < 5; ++i){
        a[i] = i * i;
    }
    for (int i = 0; i < 10; ++i){
        b[i] = 50;
    }
    c = a;
    a = b;
    delete[]b;
    delete[]c;
    return 0;
}

After executing the above code, is the memory ainitially indicated to be freed?

If not, how to free yourself?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~ ~~~~~~~~~~~~~~~

pointer amust be reserved for other purposes, so prevent its direct deletion.

The purpose of this code is to access the memory that boriginally belonged to aand free the memory used for proper operation.

+4
source share
6 answers

Yes, memory is freed. However, be very careful when changing the pointer, because it can easily lead to a memory leak.

+2
source

.

c = a;, c a, . c delete [] c;.

// Assume originally a -> 1, b -> 2

c = a;  // Now a -> 1, b -> 2, c -> 1
a = b;  // Now a -> 2, b -> 2, c -> 1

a b, , , . c.

+1

, "a" ?

, . c=a, delete [] c; a.

*c, a b

delete[]a;
delete[]b;

UPDATE

, , , .. , b a, , a. , :

1 - , a

delete []a;

2 - a , b

a=b;

, a, , a , b.

. , , a, b, , delete []a, delete []b a b .

+1

, . - , . a c. .

+1

Imho , delete , , , . , , . , :

struct Foo { 
     int id; 
     Foo(int i) : id(i) {} 
}; 
Foo* a = new Foo(1);
Foo* b = new Foo(2);
Foo* c;
c = a;
delete c;
c = b;
delete c;

delete c; c , , , , Foo id 1, , id 2.

0

Another way - you can think about optimization. You may not need to allocate memory here. See This Case

int a[5];
int b[10];

int func(int param) {
    for (int i = 0; i < 5; ++i){
        a[i] = i * i;
    }
    for (int i = 0; i < 10; ++i){
        b[i] = 50;
    }
}

int main(){
    for (int i = 0; i < 10000; ++i){
        func(i);
    }
    return 0;
}

You do not need to allocate / free memory for iteration. But if you have multithreading, it will be a little more complicated.

Using a similar method, I significantly improved the speed of calculations in a project for science.

Your code should be clear to everyone. Think about who will be after you. If the choice between readability and speed - should choose readability.

0
source

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


All Articles