Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a dynamic array automatically deallocated when it goes out of scope?

in this example

procedure foobar;
var tab:array of integer;
begin
  setlength(tab,10);
end;

is the array destroyed or the memory is leaking?

like image 834
Azarien Avatar asked Jun 24 '10 19:06

Azarien


People also ask

Why do you need to deallocate the dynamically allocated memory?

For dynamically allocated memory like “int *p = new int[10]”, it is programmers responsibility to deallocate memory when no longer needed. If programmer doesn't deallocate memory, it causes memory leak (memory is not deallocated until program terminates).

What happens if you dont delete dynamic array?

If you don't delete them, they will remain there (but won't be accessible -> this is called memory leak) until your process exits, when the operating system will deallocate them. Save this answer.

Are dynamically allocated arrays contiguous?

The right syntax for a dynamic array is int* arr = new int[5]; . Yes, it will be allocated contiguously.


2 Answers

The memory is freed. (That is, no memory leak!)

like image 69
Andreas Rejbrand Avatar answered Oct 21 '22 01:10

Andreas Rejbrand


The array is automatically freed, but I've seen obscure cases where it isn't for some reason. I solved it by setting the array to nil.

like image 20
Alan Clark Avatar answered Oct 21 '22 02:10

Alan Clark