-2

I have some code generated by MATLAB Coder. It includes some variables definitions of this type:

int tmp_size[400];

These variables are not explicitly deleted before the end of the method scope.

Are the variables allocated on the heap or the stack? Is this equivalent to the following?

int* tmp_size = new int[400];

Would it be best for memory management purposes to rewrite these variables definitions with new, like int* tmp_size = new int[400];?

I notice that memory is allocated by my program, which is never deallocated. Can this be responsible for memory leaks?

Ryan Livingston
  • 1,824
  • 10
  • 16
kiriloff
  • 22,522
  • 32
  • 127
  • 207

1 Answers1

6

These variables are of scope 'automatic'. The language guarantees that your program will release this storage at the end of the current block. It is probably on the stack, but nothing forces the implementation to use the stack. Bottom line: no leak.

bmargulies
  • 91,317
  • 38
  • 166
  • 290
  • Thanks. So that this is correct and would produce no memory leak ? – kiriloff May 22 '14 at 12:42
  • Yes that is the situation. – bmargulies May 22 '14 at 12:45
  • +1 Also, the array can be on "the heap" if, say, it is allocated in a member function of an object allocated on said "heap". It still has automatic storage duration. So the good abstraction here is storage duration, not "stack" vs "heap". – juanchopanza May 22 '14 at 12:45
  • @antitrust: correct and no memory leaks *unlike* your proposal to use `new` where you'd need a smart pointer or try/catch block to be exception safe, or to link with a garbage collector. – Tony Delroy May 22 '14 at 12:46
  • 2
    @juanchopanza: "the array can be on "the heap" if, say, it is allocated in a member function of an object allocated on said "heap"" - an object's memory location has no bearing on the member function's local variable allocation. A proper example is if the array is a member variable of an object allocated on the heap. – Tony Delroy May 22 '14 at 12:48
  • @TonyD Right. I was thinking of data members, but that doesn't apply in this case. – juanchopanza May 22 '14 at 12:56