Memory Leak examples written in 4D

517 Views Asked by At

What are some examples of developer created memory leaks written in the 4D programming language?

By developer created memory leak, i am referring to a memory leak created by bad programming that could have been avoided with better programming.


32 bit

When ran in a 32 bit application it should eventually crash once it attempts to allocate more than 2^32 bytes (4 GB) of memory. If on the Mac OS X platform, the bottom of the crash report beneath the VM Region Summary should show a memory value around 3.7 GB:

TOTAL               3.7G


64 bit

When ran in a 64 bit application the code will continue to raise the amount of memory allocated and will not plateau, in that situation the OS will eventually complain that it has ran out of memory: Imgur

1

There are 1 best solutions below

0
On

Overview

There are many ways that a developer can create there own memory leaks. Most of what you want to avoid is listed here.

  • use CLEAR VARIABLE when done using a variable
  • use CLEAR SET when done using a set
  • use CLEAR NAMED SELECTION when done using a named selection
  • use CLEAR LIST when done using a list
  • re-size your BLOBs to 0 with SET BLOB SIZE when done using the BLOB or use CLEAR VARIABLE
  • re-size your arrays to 0 when done using the array or use CLEAR VARIABLE don't forget to close any open XML trees such as XML, DOM, SVG, etc (DOM CLOSE XML, SVG_CLEAR)
  • if using ODBC always remember to free the connection using ODBC_SQLFreeConnect
  • make sure to cleanup any offscreen areas used

Examples

Here are two specific examples of developer created memory leaks:

Forgetting to close XML

Bad code:

Repeat 
  $xmlRef:=DOM Create XML Ref("root")
Until (<>crashed_or_quit)

The code snippet above will leak memory because each call to DOM CREATE XML REF will create a new reference to a memory location, while the developer of this code has neglected to include a call to free the memory. Running this in a loop in a 32 bit host application will eventually cause a crash.

Fixed code:

This code can be easily fixed by calling DOM CLOSE XML when finished with the XML reference.

Repeat 
  $xmlRef:=DOM Create XML Ref("root")   
  DOM CLOSE XML($xmlRef)  
Until (<>crashed_or_quit)  

Forgetting to clear a list

Bad code:

Repeat 
   $listRef:=New list
Until (<>crashed_or_quit)

The code snippet above will leak memory because each time NEW LIST is called a reference to a new location in memory is returned. The developer is supposed to clear the the memory at the referenced location by using the CLEAR LIST($listRef) command. As a bonus, if the list has any sublists attached, the sublists can be cleared by passing the * parameter like CLEAR LIST($listRef;*).

Fixed code:

This can be easily fixed by calling CLEAR LIST($listRef;*) as seen in the following fixed example:

Repeat 
   $listRef:=New list
   CLEAR LIST($listRef;*)
Until (<>crashed_or_quit)