C ++ - memory allocation security for an array, and then returning a pointer to be deleted from the outside

I am learning C ++ at the moment, and there is something unclear.

If I create a function that allocates memory for an array of some type and then returns a newly created pointer, given that the pointer is just a memory address, will the corresponding operator deleteclear all allocated memory correctly or only the first element will be freed, creating a memory leak with the rest of the array? If it is cleaned correctly, how does C ++ know what to release, given my supposed loss of context inherent in the return type?

int* AllocateSomething()
{
    int *arr = new int[100];
    // fill the array with something...
    return arr;
}

int main()
{
    int* p = AllocateSomething();
    delete p; // what will this do?
    delete[] p; // how would this know how much memory to delete?
}

, -, , undefined, , .

+4
5

must delete[] p, undefined. , , , . . main int, .

: dissasembly (gcc 4.8, linux x86_64):

(gdb) l AllocateSomething
1       int* AllocateSomething()
2       {
3         int *arr1 = new int[100];
4         int *arr2 = new int[200];
5         int *arr3 = new int[300];
6         int *arr4 = new int[400];
7         arr1[0] = arr2[0] = arr3[0] = arr4[0] = ~0;
8
9
10
(gdb) x/20 arr1-8
0x601ff0:       0       0       0       0
0x602000:       0       0       417     0
0x602010:       -1      0       0       0
0x602020:       0       0       0       0
0x602030:       0       0       0       0
(gdb) x/20 arr2-8
0x602190:       0       0       0       0
0x6021a0:       0       0       817     0
0x6021b0:       -1      0       0       0
0x6021c0:       0       0       0       0
0x6021d0:       0       0       0       0
(gdb) x/20 arr3-8
0x6024c0:       0       0       0       0
0x6024d0:       0       0       1217    0
0x6024e0:       -1      0       0       0
0x6024f0:       0       0       0       0
0x602500:       0       0       0       0
(gdb) x/20 arr4-8
0x602980:       0       0       0       0
0x602990:       0       0       1617    0
0x6029a0:       -1      0       0       0
0x6029b0:       0       0       0       0
0x6029c0:       0       0       0       0

. -1 . 8- (4 ints) . (sizeof (int) * ) + 17 , (8 ) .

+3

, "" (, int [], bool [] ..), , delete [], , , get undefined, "delete" .

++ 11 , , std:: unique_ptr, ( RAII).

+1

p; , .- > first
delete [] p; . →

++, : - , - . , , , . , , . , [] . , .

+1

new, . , , delete p, , . , delete [] p, , .

+1

, ++ ,

[] "" ?

, . "" , . , - , .

+1

All Articles