Does a dynamically allocated array return from a function causing a memory leak?

I ask this question to get rid of the confusion that I experienced about the next program. I know that using an array in certain contexts will cause the array to decay to a single pointer to its first element. I have a function that returns this array by pointer (this function is created using new[]). Will the array decay, forcing the pointer to point to only the first element? Here is an example:

int *foo() {
    int *t = new int[10];

    return t;
}

int main() {
    int *p = foo();
}

There is confusion here. I do not know if it points to pthe first element or to the entire array. Therefore, I have the following questions:

  • Does the array return a pointer, leading to its decay (and, therefore, causes a memory leak)?
  • p ?
  • delete[] on p undefined, ?

, , . .

+5
3

, , , .

, . , , delete[]. , . , !

. ( ), . , , ( ) ( ).

. :

, , , , , , .

/ , , delete[], . . , , , "out".

++ , , std::vector std::map, , , " ?" .

+6

(, , )?

t, . . , delete [] .

p ?

delete [] p undefined, ?

, . .

: , , , . , , delete, delete [] . : ! , beter , , , (std::vector, std::array, std::unique_ptr, std::shared_ptr...).

+7

delete [] p undefined, ?

, [] p !

However, delete [] magically knows how long the array is, sizeof (p) does not work, because the allocator keeps track of the allocated space. However, sizeof is a fixed value generated in compiletime

0
source

All Articles