TweetFollow Us on Twitter

About Memory
Volume Number:1
Issue Number:7
Column Tag:BASIC SChool

Memory Management in Tight Spaces

By Dave Kelly

Of major concern in any program development is that of memory management. This is especially true on the 128K Macintosh. MSBasic leaves only about 14K free program space to work with. However, on the 512K Mac there is over 330K free program space. If you are disappointed by the memory limitations there are some ways which you may get around some of the limitations.

There are three different areas of memory which you can have control over:

• The stack

• The Heap

• BASIC’s data segment

The Stack and the Heap

Macintosh applications can allocate and release memory by using the stack or the heap. The stack is used to temporarily store information telling BASIC where to return to from GOSUBs, FOR NEXT loops, WHILE WEND, subprogram calls and nested user defined functions. The Macintosh ROM routines require alot of stack space depending on the number of levels of nesting of controls (such as BUTTONS, EDIT FIELDS). The information on the stack is stored in LIFO (last-in-first-out) order. The last item put on the stack is always the first to be removed. The information is always released at the top of the stack, never in the middle, so there can never be blank “holes” in the stack. As in figure 1, the stack starts at a fixed address in high memory and as information is added to the stack it grows toward low memory (top of stack).

The heap contains blocks of memory which are allocated and released as needed by the Macintosh Operating System’s Memory Manager. The Memory Manager keeps track of the heap section of memory and “compacts” the heap if necessary in order to conserve the heap space. If you notice when you load BASIC only a part of BASIC loads at a time. Part of BASIC is in memory, and the rest is in sections that are loaded into memory as needed. Because the heap is smaller on the 128K Mac, there is considerably more disk access involved as sections of BASIC are swapped in and out of the heap. Whenever you use any of the Macintosh “features” such as MENU, BUTTON, EDIT FIELD, PICTURE, SOUND, WAVE, or WINDOW, a part of the heap is used to keep track of these “resources”. Open desk accessories also use a portion of the heap. The heap starts at low memory and adds blocks toward high memory. After a program has been running for awhile the heap will become fragmented with “holes” in the middle as various resources are released. By closing WINDOWs, MENUs and closing desk applications memory can be made available in the stack for other resources. The SOUND/WAVE buffer can be released (1024 bytes of heap) by using a WAVE 0 statement when it is no longer needed. Also a PICTURE ON immediately followed by PICTURE OFF will reclaim memory which was used by a previous picture that was in the heap. The Memory Manager will compact the contents of the heap.

One note on the speed of your programs as it pertains to the heap. I have found that when first defining EDIT FIELD and BUTTON controls that it takes longer the first time through the program while the heap allocates memory to keep the BUTTON and EDIT FIELD resources. Re-opening a window that had been closed which contains buttons and edit fields will use the same resources which were previously allocated in the heap. There are always two heap areas in memory: the system heap, which is used by the Toolbox and Operating System, and the application heap, which is used by the application program (in our case the application is MSBASIC).

The BASIC data segment area of memory is the area used to store the BASIC program and variables. This area also contains area for file buffers for opened files.

CLEAR AND FRE(n)

MSBASIC has provided the CLEAR statement to allocate memory to the three areas of RAM mentioned above. The CLEAR statement adjusts the number of bytes reserved for the stack and the data segment. The syntax is:

CLEAR [,[data-segment-size ][, stack-size ]]

The remaining RAM is left for the heap space. The heap space is calculated by taking the total amount of RAM (128K or 512K) minus the data segment size and the stack size ( heap = Total RAM - ( data-segment-size + stack-size )). For most programs on a 512K Mac it is not necessary to use the CLEAR statement, but it is needed for many programs to run on the 128K Mac. You should keep this in mind if you intend for your programs to run on any Mac (128K or 512K). You can use the statement FRE(n ) to find out how much free memory is available in each part of RAM. FRE(-1) returns the amount of free memory in the heap. FRE (-2) returns the amount of stack which has never been used. By using this value the program can be adjusted using CLEAR to use memory the most efficiently. Be sure that the worst case is used when fine tuning the memory. If (n ) is (“ “) or any other number (except -1 or -2) the expression returns the number of free bytes available in BASIC’s data segment. All of the FRE statements will compact string space. Each time a string is defined in BASIC part of the data segment area of memory is used. After swapping and shuffling strings around in your program the data segment becomes full of strings, most of which are no longer needed. For example if a string A$ is assigned as “MACINTOSH” and then reassigned as “MACTUTOR” , new space is allotted for “MACTUTOR” but the old string still exists in memory. A$ would only point to the most recent assignment of A$. By using the FRE( n ) statement, garbage collection is done and all the currently assigned strings are compacted in the data segment of memory.

USING RUN OR CHAIN

If you find that using the CLEAR statement still doesn’t give you enough memory you can split your program into subprograms and load in each program as needed. The RUN statement may be used to load and execute another BASIC program. The syntax is RUN filename[,R]. The R added to the end of the statement will cause all open data files to remain open. The problem with using the RUN statements is that when RUN executes all variables are erased. This means that all variables which are needed in the next program segment would need to be saved (temporarily) to the disk. RUN is best used to load new programs that are independent from the calling program.

To preserve your variables you should use the CHAIN statement. The syntax is: CHAIN [ MERGE ]filespec [,[expression ] [,ALL ][, DELETE range ]]] . The MERGE statement appends the called program to the end of the program currently in memory. The called program must have been saved as an ASCII file for this to work. filespec is the specification (disk name and filename) and expression is an expression or line number which tells BASIC where to start executing the called program. An alphanumeric label may not be used as this expression. If you use the ALL option, all the variables in the current program in memory are passed to the called program. The DELETE statement is used to delete lines of program currently in memory to make room for the called program. The BASIC manual is clear describing the syntax used here.

CHOOSING YOUR FILENAME

Some of these statements may seem to be somewhat trivial, but it takes some planning to determine when and how each section of program should be loaded and executed. The program FILE$ Demo demonstrates a way that the user can select which program or file to use. The function FILE$(n [,prompt-string ]) is supplied by MSBASIC to allow various types of files to be selected using the mini-finder dialog box. I’m sure that we are familiar with it from using it in most applications.

Fig. 1 Selection of file types

The parameter n is a number 0 or 1. FILE$(0) calls a dialog box which prompts the user for the name of a file. The prompt-string is displayed as the default filename. This is useful when you want to let the user decide which filename to use to save data to the disk. FILE$(1) calls up the mini-finder dialog box and prompts the user to select a filename in the list. You can use this to select files in either disk drive or on other disks. Both commands return the name of the file selected. This filename can then be used to load or save data or to call a new program. The prompt- string in the FILE$(1) statement contains a list of the file types, 4 characters per type. The file type is attached to the filename in the directory and the finder uses it to know what kind of file each icon represents.

In the demo program a window opens and asks for the user to select the type or types that should be included in the file selection. This way certain types of files could be screened out. The basic stores files as TEXT, but the type may be changed by using the NAME statement. In this way you could use a special type that “belongs” only to your program. If no types are selected in the demo program, then the prompt-string is blank and all types are selected. After the desired type buttons are selected selecting the “Select Files” button will execute the FILE$(1) statement and the mini-finder dialog box will appear. Select a filename and push the open button and you can see the format that is returned by the FILE$(1) statement. There are many possible ways that this could be used which are left to you to decide for your particular programing application.

Any particular topic that you would like to see covered in MacTutor? Write to us!

Fig. 2  Standard File Interface
‘    FILE$() Demo 
‘    by David Kelly
‘    ©MACTUTOR 1985

‘ Erase menus
FOR i=1 TO 5
    MENU i,0,0,””
NEXT
WINDOW 1,,(15,40)-(495,245),2

‘ initialize button status flags
FOR i=1 TO 7
    btn(i)=1
NEXT
Begin:   ‘Set up button controls
BUTTON 1,btn(1),”MacWrite Files”,  (119,15)-(237,30),3

Fig. 3 Program output


BUTTON 2,btn(2),”Text Files”, (119,40)-(200,55),3
BUTTON 3,btn(3),”MSBASIC 1.0 Files”, (119,65)-(252,80),3
BUTTON 4,btn(4),”MSBASIC 2.0 Decimal Files”,(119,90)-(307,105),3
BUTTON 5,btn(5),”MSBASIC 2.0 Binary  Files”,(119,115)-(317,130),3
BUTTON 6,btn(6),”MacPaint Files”,  (119,140)-(233,155),3
BUTTON 7,btn(7),”Applications”,    (119,165)-(219,180),3
BUTTON 8,1,”Select Files”,(363,87)-(448,121)
BUTTON 9,1,”Abort”,(363,131)-(448,165)
‘ Wait for button push
loop:WHILE DIALOG(0) <>1:WEND
        buttonpushed=DIALOG(1)
        IF buttonpushed=8 THEN seefiles
        IF buttonpushed=9 THEN WINDOW  CLOSE 1:MENU RESET:END
        IF btn(buttonpushed)=1 THEN  btn(buttonpushed)=2 ELSE  
 btn(buttonpushed)=1
        BUTTON buttonpushed,btn(buttonpushed)
GOTO loop
seefiles:

‘    MSBA    Basic 1.0
‘    MSBB    Basic 2.0 Decimal version
‘    MSBC    Basic 2.0 Binary version
‘    TEXT    Text file
‘    APPL    Application
‘    PNTG    MacPaint File
‘    WORD    MacWrite File
‘    MPRJ    MacProject File
‘ Other types may be added 

type$=””
IF btn(1)=2 THEN type$=type$+”WORD”
IF btn(2)=2 THEN type$=type$+”TEXT”
IF btn(3)=2 THEN type$=type$+”MSBA”
IF btn(4)=2 THEN type$=type$+”MSBB”
IF btn(5)=2 THEN type$=type$+”MSBC”
IF btn(6)=2 THEN type$=type$+”PNTG”
IF btn(7)=2 THEN type$=type$+”APPL”
selection$=FILES$(1,type$)
IF selection$=””THEN loop

‘ Close buttons
FOR i=1 TO 9
        BUTTON CLOSE i
NEXT

PRINT “You have selected “;
CALL TEXTFACE(1)
PRINT selection$
CALL TEXTFACE(0)
PRINT “Types =”;type$
BUTTON 1,1,”More”,(363,87)-(448,121)
BUTTON 2,1,”Abort”,(363,131)-(448,165)

‘ Wait for button push
WHILE DIALOG(0) <>1:WEND
        buttonpushed=DIALOG(1)
        IF buttonpushed=1 THEN CLS
     GOTO Begin
        WINDOW CLOSE 1:MENU RESET:END

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.