Home > General > Another discussion about stack vs. heap

Another discussion about stack vs. heap

January 14th, 2008

In post “Stack vs. Heap“, we have discussed about stack and heap, and given the simple rules on the choice of stack or heap. And today, we give some simple examples for a clear image.

Typically, if an element does not need to exist beyond the scope of its variable, you are much better off allocating it on the stack instead of the heap.  Objects that need to have a lifetime beyond the local scope must be allocated on the heap. 

It is common to allocate objects whose size is not known at compile time on the heap, although in this case the preferred method depends on the lifetime; for values needed within the local scope, CArray or std::vector are a better choice than a raw malloc or new because the destructors of these objects ensure that the object is properly deallocated when you leave scope.

Case 1:

Poor strategy:

CMyDIalog * dlg = new CMyDialog;
dlg->DoModal();
//…
delete dlg;

Good strategy:

CMyDialog dlg;
dlg.DoModal();
//…

Case 2:

Poor strategy:

LPBYTE b = new BYTE[size];
//…
delete b;

Good strategy:

CByteArray b;
b.SetSize(size);

or

std::vector<BYTE> b;
b.resize(size);

Case 3:

Poor strategy:

LPDWORD d = new DWORD;
*d = 0;
Function1(d);
//…
delete d;

Good strategy:

DWORD d = 0;
Function1(&d);
// …

Case 4:

Poor strategy(failing strategy):

TCHAR buffer[COMPILE_TIME_SIZE];
read_stuff_into(buffer);
PostMessage(WM_USE_DATA, (WPARAM)buffer);

Good strategy:

TCHAR buffer[COMPILE_TIME_SIZE];
read_stuff_into(buffer);
SendMessage(WM_USE_DATA, (WPARAM)buffer);

or

TCHAR * buffer = new TCHAR[COMPILE_TIME_SIZE];
read_stuff_into(buffer);
PostMessage(WM_USE_DATA, (WPARAM)buffer);  //delete the pointer in the message handler

The above case shows that the object needs to exist beyond the scope of the function in which it is declared.

Bottom line:

If you don’t need to put it on the heap, don’t put it on the heap. 

If you need to put it on the heap (as CArray and std::vector do for their contents) avoid situations in which an explicit delete is required. 

If you need it to exist for a long time, put it on the heap.

–POST by Joe (newco.at.flounder.com)

General , ,

  1. No comments yet.
  1. No trackbacks yet.