• Keine Ergebnisse gefunden

LATTICE,INC. @ file file \lc\l) it

N/A
N/A
Protected

Academic year: 2022

Aktie "LATTICE,INC. @ file file \lc\l) it"

Copied!
272
0
0

Wird geladen.... (Jetzt Volltext ansehen)

Volltext

(1)@. LATTICE,INC. P. O. BOX 3072. ·GLENÉLLYN·LLNOIS. 60138·. 3l2/858ñ9!5OU1NX9lO29l-2l9O. BULLETIN. TECHNICAL. TB841101.001 November DATE: 1, 1984 PRODUCT: 8086/8088 C Compiler Known Bugs SUBjECT: in Version. 2.14. and Recently bugs concerning the Version 2.14 libraries three Two of these pertain to the startup modules have come to light. and the other concerns sensing and use of the 8087 co-processor, under MS-DOS 1 in the use of the "malloc'° and "getmem" functions P models of the compiler. some the s and code was In addition oMtted from the file " main.c".. 1. Floating. Point. Bugs 8087. cjf the. (a) Sensing. The technique employed in the run-time library to sense of the 8087 co-processor does not work in the presence V2.14 because the 8087 is not initialized prior to the need You Correcting this problem is rather easy. test. add a line of code to the only °'c.asm" provided with and compiler reassemble this the the to replace current "c.obj".. file. In. the. file. "c.asm" CALL. just prior. to. you. Then reassemble follows:. find. a. line:. JLAIN. this line, DB. will. file. insert. ODBh,OE3h. "c.asm". ;. for. the fcülowing FNINIT. each of the. "c.asm". the appropriate -- (i.e., \lc\s, to\lc\d, \lc\p, or same directory as the Copy. in appropriate. --. Use. the. memory. mcdel.. command. 1. line instruction models. memory. model. \lc\l) "dos.mac". as. subdirectory that is for the. so. it.

(2) @. LATTICE,1NC. P. O. BOX 3Q72 ·GL£N. masm. ELLYN ·ILLNO1S. 60138. W. ·. 312/858-7950·TWX9lO291-2. c;. into "c.obj".. to assemble "c.asm". "DB" a here as pseudo-op is specified instruction than an "FFNIT' instruction since many assemblers rather do handle not properly floating point instructions. Should your assembler be able to handle such instructions, be sure to use an "FNINIT" instruction rather than "FINIT" Qr else the assembler will generate a "WAIT" instruction to the °'FINIT" and resulting wait programs will prior on machines not containing endlessly a co-processor. The. (b). Floating. Point. in the. D. arid. L. Mdels. In attempting accidentally the correct. to repair an earlier bug concerning the 8087 To broke its use in the D and L models. problem to patch the you can use "debug" as follows. "lcmd.lib" and "lcml.lib" libraries Each (Underlined portions are what you must type. line be entered with a carriage must return.) we. (i). Patching >debuq -eA97A -eA9CC. lcmd.lib lcmd.lib 10.12 78.76. -W -SI >. (ii). Patching Aebug -eBB71 -eBBC7. lcml.lib Icínl.Iíb 12.14. 3D.3B. -W. -g >. (C}. Bug. in. 8087. Library. Under certain Cxd55 function. Divide. circumstances will return 2. Routine the floating point the incorrect value. division. when. an.

(3) @. LATTICE, INC. P. O. BOX 3072. ·. GLEN ELLYN. ·. LUNOIS. 60138. ·. is present since this function This bug restore the DI register. future release . 8087. (2) Ma1loc. and. Getmem. under. MS-DOS. 312/858-7950. fails will be. ·. TWX. 9lO29l-2l90. to save and repaired in a. 1. model P functions The S and allocation values library memory and in "getmem" will n<jt return the correct "malloc" of an running under MS-DOS 1 when a call to one application allocated to exceed 6 4K. would cause the total memory these returned In particular the failure value of NULL will not be be fixed in a future in willD and this andcase. doesThis problem the L modelm not effect release,. it. (. 'L main.c" last "exit(O);" statement. 3) Omission The. in. Ñifndef '. should. TINY. exit(0); #else exit(0); Tencí. if. ***. END. 3. **". be. replaced. with.

(4) @. LATTICE,INC. P. O. BOX 3072. · awELLvN·. LLINOQS 6Ol380. TECHNICAL. JR/B58J950·TWX9I029I-2I%. BULLETIN. TB8410¶0.001 1984 TO, DATE: october PRODUCT: 8086/8080 C Compiler SUBjECT: Ver3ion 2.14 Update. VerMon correct. 2.14 of the the following. 8D86/808B. C. compiler. hm been released. to. problenm. were built in 8UCÍll In VerMon 2,¶3, the S model libr&ríeg did not me the that the floating poInt operattom The model$ worked other memory pregent. 8087 chip 1.. a. way. correctly.. ff. the PUTC problem In VerMon 2.fj, we broke 2. Klhíle ffxfng mich & way that buffer8 the level 2 buffer flmh functionThlg9n would written twice. mnnethnes occur when you did were re&dg or vrítm. intervening several FSEEKg without 3. UNGETC did not alwayg work correctly under the d md L modelg, depending on where the buffer ma® lomted.. 000END$0*. 1.

(5) @. LATTICE,INC. P. O BOX. 3on·cA£NELlNN·LLlNo|s6oí38·. 3u/85B-795o0Twx9m9l.2l9o. BULLETIN. TECHNICAL. TB8410¶0.002 DATE: October tO, 1984 PRODUCT: 8086/0088 C Complier SUBjECT:. Insufficient. Memory. Mesmge. In bulletfn TB840914.otn we mentioned a problem observed during in an "!nsuff!cient the tesMng of vergjcyn 2.13 that resulted memory" message. At that tfme, we believed that the message was from Hs-ljOS. Hell, we must admit with a blush that orSgínatfng C.ASl'l, was mdule. coming from the message our start-up. this meggage wá3 that we forked a child jU9t barely into the available memory. After loading the .EXE file, FfS-ljOS passed control to C.ASM C.ASM then attempted the child procesg at the entry point. gtack and he€p 8pace for the C program, but there wá9 to allocate When C.ASK dlmplayed the not enough memory. that occurred, '°ínsufficient memory" me33age and aborted with a non-zero exit code. The. situation wttcjse. prDc'e53. leading .EXE. file. to. fit. The. migtake we made in our tmt program w39 to examine only the an return code from the FORKL function. Thig wIll indicate error and MS-DOS wá9 gpace only unable to obtain the needed load the U3ed &Ííorj He WAIT to functfon ch9ld program. should have the check the exit code from the child.. If. ""END°"". E.

(6) @. LATTICE,INC. P O DOX 3072·GLENELLYN·LLNOS. 60138·. 312/858795O·TwX91O29i-2l9O. BULLETIN. TECHNICAL. TBB41010.003 WLTE: October 10, 1984 PRODUCT: 8086/8088 C Compiler SUBJEC"I); Combining LC and LCM. In and. TB840914.OQI LCM. we. librarfes.. Librar!eg. g&ve a Mmple procedure Some people who symbol me3gageg duplicate. for. tried this. concerned about the Here is a better procedure:. to create. 1. Use editor your favorite the following: containing. combtnlng the LC procedure became that regulted.. file. the. MIXLC.LNK. Icc.lfb tí lcm.líb fL lc.lib exc _pfmt,cprlntf,fprintf,printf,gprintf bu. exc. gfmt,c8canf,fgcanf,gcanf,g5c8nf. —. model, copy MIXLC.LNK is g, p, d, or I. directory, and execute PLIB86. 2. For each. directory, into that plib86. into. memory. where. x. Then &g. U9é. the CD. \lc\x. to get. follows:. émlxlc. Thig procedure creatm a combined library LCC.LIB which ínclude3 you vant functlonm the complete verMons of the PRINTF/SCANF Mmply verMons, contains the abbreviated 8 combined library that commandg In HIXLC.LNK. the two Interchange. If. "ft". "'"END000. 1.

(7) @. LATTICE, INC. jon·gLENEtlYN·LlNcMs. P O BOX. TECHNICAL. 6Olj8 · 312/858795O·TWx9l029l.2l9O. BULLETIN. TB8U)9ICOO1 1984 DATE: September PRODUCT: 8086/8088 C Compiler SUBJECT: Version 2.¶3 UHate. u,. VerMOn correct. I.. when. 2.1J of the 8086/8088 C compiler problems: the following STRCMP. and. STRNC6IP. string3. ccmparlng. j.. wag. The an. did. PUTC. not work correctíY. of a floatfng-polnt divide-by-zero results 8087 installed were not the Bame 88 when. to. results. the correct did not return of unequal lengthm. form8 of 2. The various the D and L modelm with. has been relemed. under operation the 8007. removed.. 4. Several (a). problems. in the varÍoü8. exi8ted. FORK. environment 8trlng array va8 sot pamed to the child Process under the S &nd. The. correctly models. tb). An. functfonm. extra. variable. by rejected. P memory. backslash wa8 appended to the PATH but accepted by PCDOS, ThG wm usually MSDOS 9otñe fmplementationm. waB. The of default FCBS did not Hop vhen construction This argument beginnfng with a Uash w33 reached. caused problem for 8ocñe older programs that relied on by command the FCB setup done the MSDOS processor.. (C). an. (d) .COM. The. keep the generated. logic searched for a Thi8 hag been reversed .EXE around even version. fork. fije.. a. .COM.. 1. file. before a because some people after they have .EXE.

(8) @. LATÍ1CE, INC. P.. O. BOX 3072. (e. ). A. GLEN ELLYN. ·. ·. UNOSS. 60138. ·. JJ2/858. 7950·. JWX 910 291 219'. return was not appended to the generated to which caused some forked programs. carriage. string,. command fat I .. showed These problems usually up when you tried to fork the command to use processor or when the chi Id process attempted Td sImplify the invocation of the inherited environment. SYSTEI·) we've addeQ & UNIX-compatfble the command processor, The function has one argument, the command f unct ion. For exemple, gtríng, and returns the same results as FORKL.. systemC"dir. calls the drSve A.. a:. command. ") to display. processor. the. directory. frorn. we observed Nhíle testing the fork functions, what appears Hhen system cannot the operating to be an HS-IJOS bug. enough memory to load the child prográm, obtain supposed to return error cocjé B that we wIll then pass back However, En some cases, t·lS-DOS displays to you In _oserr. on the screen and returns the message "jnsuf f lcient memDTy" This has been observed on PC-DOS 2.1 and a succem code. 3.0 running on the IBH-XT and IBH-AT and in the version of MS-DOS currently running on the TANDY us 2000. We are pursuing anybody can give a solution, but any further we vould appreciate the help. informatfon,. it's. if. f unctions did not viork correctly under 5. The SETJHP/LONGJKP a change in required the p mode! . Note that thh correctfon and that ALL PROGRAPIS USING THIS header the SETJMP.H model MUST BE RE-COHPILED HEADER of which memory regard)esg they employ.. file. of the 8087 .did not work 6. Detection using an 80286, such ag the IBI4-AT. 7.. The. POW. function. did. not always. correctly. return. on. sYstems. the correct. result. way Several people complained that the libraries became we Therefore, larqqe uhen we added the math functions. model into two have sp the library for each memory LCV.L,IB for memorY the "core functSons" contains pieces. mode! the floating point math contains x, and I.CMX.LIEj B.. tejo. it. 2.

(9) @. LATTICE,INC. P O. BOX. 3072. ·GLEÑELLYN·LLNOS60138. ·. 3l2/858-7950·l"WX9lO-29l-2l9O. If you need to useLC both libraries, make sure mentioned before at link time. you are is that also using our CF(JOD Smorgasbord, its library (LCX) should be mentioned before LCFI. At this time we are pretty place, confident that the library wa3 split in the correct problems that we but you find any interdependence overlooked, please report them to lbS. you want to recombine the two libraries, use PLIB86, as follows: functions.. If. LCM. if. If. lc.lib lcc.lib lcc.lib,lcm.lib lc.lib fi. ren plib86. bu. for the batch files that we've been supplying The release LLNKx.BAT, OtÁY use LC.LIB. LINKMX.BAT some new that disks include batch files named and both LC61.LIB LC.LIB. Note. that. linking,. named. use. be and of the PRINTF aware that two versions provided. don't use LCM.LIB, you are families support point you'll get a vergton that does not floatln3 module. conversÍoñ3, which saves about 3 Kbytes in the loa PRINTF and SCANF conversion With LCM.LIB, you get the You SCÁNF. snould. also. If. full. capabilities. 9. we've. eliminated the need for TINYMAIN.C by putting compilation statements into _MAIN.C, and the conditional pre-comptled of the versiom release disks now contain where x i3 the under the names abbrev¡ated0_bjAIN jQAINx.OBj, MAIN, you memory model (S,P,D, or L). need to recompile versTon. -dTINY=1 to get the abbreviated use the LC option. If. The LC contain the of J4AIN, version libraries supports version which is the default. Because this and stderr force3 all of the the stdin, stdout, files, you don't need level 2. I/O functions andto be included. these standard files be don't useby any level 2 I/O, your reduced using the abbreviated load module size will version;. still. full full it If. *'*END"° J.

(10) LIFEBOAT a. 8. S. O. C. i. a. t. 8. 0. LMtice C Manual kMiao. ~~. cc·mNM. Fumtbnd. Released. DescripHon. 25,. Nty. 1982. Nkmud This document describes the compiler Revision 2 and librory.. d. Copyright ". Supplement. Note:. Qppended. May. Published by: Lifeboat Associates 1651 Third Avenue New York, New York ÍOÍ28. Tefe: (212)8600300 Telex: 424490 (LBSOFT. 1982,. Ul). )984. by. Inc.. Lattice,. 29,. to. üjttice C v. 2.) document. to this )984..

(11) PREFACE. in softwarz products based Lattice, Inc., a developer of portable C for own Lattice its originally developed Illinois When introduced a minicomputer. the IBM PC was internal use on company a for developing recognized the potential the in 1981, 16-bit of for the C programming language full implementationLifeboat a New York-based software Associates,. Chicago,. microcomputers. the with funding which enabled then provided Lattice publisher, C company is believed that Lattice to make the conversion. It "ported" was the first minicomputer product successfully to the based PC. IBM Washington, in Bellevu.e, In 1983, Microsoft, C. C to become Microsoft Also in 1983, Lattice selected Lattice 68000 Motorola version a developed of its compiler for the B-bit and CP/M-based cross-compiler for a 280 microprocessor MS-DOS 2.0 with Revision 2, Lattice C implements microsystems. models, giving software developers the pathnames and large memory and which can better data structures programs ability to create memory on 8086/8088-based available systems. utilize the large. TRADEMARK. ACKNCMLEDOBNT8. Lattice 18is. a. regi8tered trademark of Lattice, Inc. regi8tered trademark of Kicro8oft, Inc. is a registered trademark of Digital Re8earch, Laboratoriem a is trademark of Bell Telephone of Intel Corporation. Intel 18 a18 trademark a trademark of Motorola Corp. Motorola 280 a is trademark of Zilog, Inc. MS-DOS CP/M UNIX. a. Inc..

(12) TABLE. Section. l. Section. 2. 2.1. 2.3 Section 3.1. Language. 2-l. 2.1.1 2.1.2. Differ>"nccs. Major. Language. 2.2.1 2.2.2 2.2.3 2.2.4 2.2.5 2.2.6 2.2.7 2.2.8. Pre-processor Features Arithmetic objects Derived Objects Storage Classes Scopc' of Identifiers. Arbitíary. from the Standard LimIt3tions. Control. Library. I/O. Level Level Level. and. Utility 3.3.1 3.3.2 3.3.3 3.3.4. 2-5 2-6 2-6 2-B. 2-8 2-9. l. Manual. Memory Memory Memory. Allocation Allocation Allocation. Functiom. System. I/O FUnction8 and Macros Level Level I I/O Functiom Direct Console K/O Functions program Exit Functiom 2. Functions Memory. and. Macros. Utilities lqacro8. Character Type String Utility. Utility. Macros. 2-ll 2-ll. Functions Functions. mmory Allocation 3 2. Reference. 2-3. 2-G. Flow C. 2-l 2-4. Features. Initializers Expression Evaluation. Portable. 3.2.1 3.2.2 3.2.3 3.2.4 J.3. Definition of Mfferenc"."s. 3.1.1 3.1.2 3.1.3 3.2. I-L. Comparison to the 3. CONTENTS. Introduction. Summary. 2.2. OF. Functions. 3-l 3-2 3-6 3-12 3-lS 3-15 3-40 3-49 3-56 3-59 3-59 3-63 3-64 3-83.

(13) Section. 4. 4.1. Compiler. 4.2.1 4.2.2 4.2.3 4.2.4 4.2.5 4.2.6 4.2.7. 4-l 4-3 4-7 4-8 4-9 4-13 4-15. l. 2. Program Linking Program Execution Function Extract Utility object Module Dissassembler. Data Elements Names External Include File Processing Operations and Arithmetic Floating Point Operations Fields Bit Register Variables. Compiler. 4.3. 4.3.1 4.3.2 4.3.3 4.3.4 4.4. Memory. 4.4.1 4.4.2 4.4.3 4.4.4 4.4.5 4.4.6. 4.5.1 4.5.2 4.5.3 4.5.4 4.5.4 5. Phase Phase. Conversions. Error. Code. 4-18 4-19 4-20 4-20 4-21 4-22 4-23 4-23. l. 2. Processing Generation. 4-23 4-24 4-25 4-25. Models. Áddressing. Model Choo8ing the Memory Compiling the Memory Models Linking Program8 Code Generation for Pointer Operations The -s option for Four-byte Pointers Creating an Array Greater than 64K. Program Structure. object Code Conventiom Linkage Conventions Function Call Conventiom Assembly Language Interface Stack Overflow Detection. System Library. 4-28 4-29 4-30 4-30 4-32 4-33 4-34 4-36 4-37 4-38 4-40 4-44. Implementation. I/O Device I/O Memory Allocation Program Entry/Exit Special Functions. File. 4-18. Processing. Run-time. 4.5. 5.1 5.2 5.3 5.4 5.5. Phase Phase. Machine Dependencies. 4.2. Section. Implementation. Instructions. Operating 4.1.1 4.1.2 4.1.3 4.1.4 4.1.5 4.1.6. Run-time. and. 5-l 5-2 5-4 5-5 5-5.

(14) Lattice. 8086/8088. SECTION. I:. C. Compiler. Introduction. Introduction. a provides This document functional an description of C compiler, a portable implementation of the Lattice compiler for makes Ca programming language called high no the level It either programming fundamentals or how attempt to discuss to C made progEam in Extensive reference is to the itself. The C, by Proqramming Language, text Brian W. Kernighan definitive and Englewood New (Prentice-Hall, Dennis M. Ritchie Cliffs, Inc., C 1978). This description of Lattice incomplete jersey, is and Ritchie without the Kernighan is called, which text, as also provides an excellent to the language. tutorial introduction. it. l.l. Documentation. manual is divided into five sections. First, this introduction. Second, the language accepted by the compiler, which differs from the standard in only a few minor details, is The described. section presents the portable third library and functions in functional groups with calling sequences and examples. Fourth, the details of the compiler run-time execution for program are presented this implementation, including detailed operating instructions, machine dependencies, and the operating program structure. system interfaces Fifth, in terms of the portable functions are described library (file naming conventions, provided with etc.) and the special functions implementation. this The. this document is intended to serve as a reference manual, each topic presented in full technical is is usually detail as Some encountered. reference to'sections not yet encountered is unavoidable, but thege references are gpecificalIy noted. as. it. an overview of the compiler, to get read the first portion of each of the major suMections in the implementation description summary (Section 4), language the beginning the at of the language at definition (Section 2), and the function summaries and beginning the of the (Section 3), the library groups introductions in the system to the subsections interface messages information (Section S). Error in are described Appendix A and error reporting procedures in Appendix B. Method8 C of converting for CP/M microcomputer gygtems programs written a in Appendix c. of are de3cribed files Mipped with C D. contained in Appendix Lattice are. list. I-l.

(15) Lattice. 8086/8088. C. Compiler. Language. Definition. 2:. SECTION. Language. Definition. Lattice portable C compiler accepts a program written in the programming determines language, the elementary actions and by specified that eventually translates those program, actions into machine language instructions. Although the final is highly machine-dependent, the actual result of these processes by accepted the compiler language is, for the most Dart, independent of any sYstem This or implementation details. by C section the Lattice compiler presents the language defined and (K&R) The C using the Kernighan Ritchie Programming text a reference point. Since this language conforms Lanquaqe as closely to that described in the text, only the major differences The presented. major features of the language are then are discussed, not in any attempt at completeness, but simply for the sake of showing them from a different perspective. Finally, a comparison with the Kernigban and Ritchie "C Reference Manual" is made how more precisely implementation the Lattice to show differs from the standard. The C. first. 2.1. Summary. of Differences. There that appear in a discussion are two classes of differences The of an implementation of a programmÍng language. first class is that of actual semantic differences; that is, variations which The second to differ. cause the meaning of language constructs a reflection of the practical is merely class limitations Eachto which all programs including compilers are subject. --of subsections the following presents the respective details for the Lattice implementation of C. 2.1.1. Differences. from the Standard. Deviating from a standard has its own peculiar set of perils and On rewards. the one hand, the differences create problems for who have on those conformed to the standard in the past; the other, they may make easier for those who take advantage of them in the future. of the differences Most listed below were and prompted by a desire to make the language both more portable The more comprehensible. majority of vast not programs will these Potential troublespots; those that do will in encounter be improved by adjusting most cases to conform to them. Here, then, is a summary of the major differences:. life. normally can be nested in the Lattice compiler; A compile-time the standard, option forces they cannot. mode. compiler back to the standard non-nesting. o. Comments. o. Pre-processor using arguments must be macro substitutions on a single specified line; for example, when max(a,b) is used, the invocation text from max to the final closing parenthesis must be defined within a single input line.. in the. 2~1.

(16) Lattice. o. 8086/8088. C. Compiler. Definition. Language. The. dollar sign (S) is permitted as an embedded (i.e., not first) character in identifiers. string constants refer to the same Identically written that is, only one copy of the static storage location; by the compiler. This is in contrast to string is generated the statement in Kernighan and Ritchie that all strings are when written distinct, even identically. Multiple character constants are accepted by this compiler; a in the. o. o. the standard, single character only enclosed in single The resulting quotes is legal. value may be @9,FE or long, and its exact value is machine-dependent. o. and union member In processing structure declarations, the each a separate compiler builds names of member for Thus, identical names may be used for (or union). structure members in different structures, even though both the offset and the attributes may be different in each declaration. The being referenced determines which structure specific member (and name therefore which offset and of set attributes) is meant. The typing sorules for structure member refeEences are strictly enforced that the patticular list be determined. names can of valid member In other words, expression in front of the . or -> operators the must be identifiable by the compiler as a structure or pointer to a of a definite type. strueture. iist. o. conversion (by assignment) is but legal Implicit pointer generates a warning message; occurs whenever any value this other than a pointer of the same type or the constant zero be used A cast operator can is assigned to a pointer. to A more the warning. eliminate stringent requirement is enforced for where the expression to initializers, must a pointer evaluate to a pointer of the same initialize type or to the constant zero; any other value is an error.. o. a function argument of union appears as If a structure &, without being preceded by the address-of the operator and a message assumes compiler warning that generates the was intended. address of the aggregate. o. An. o. The. A. &; operator array name may be preceded by the address-of the meaning, however, is not that of a pointer to the first element but of a pointer to the array. This construct allows initialization of pointers to arrays. an following constant expression may statement not contain the sizeof operator completed in less than a single line.. more. differences important 2-2. tif. conditional and. must. and systematic detailed explanation of the is presented in Section 2.3, but some of the above items deserve immediate clarification.. be. above most.

(17) Lattice. 8086/8088. C. Compiler. Language. Definition. and names a intent behind making the structure union member class of for each structure separate is twofold. identifiers names of member is greatly increased, First, nowthe flexibility need since the programmer not worry about a possible conflict of names between different structures. Second, the requirement that the compiler be able to determine the type of the structure and being referenced generally improves the clarity of the code, as disallows such questionable constructs The. int. *p;. © D. U. p->xyz. =. 4;. Those who which is considered an error by this compiler. grumble accomplish about that one can. the this restriction should Cnote by equivalent using a cast: sequence in Lattice. ((struct The. parentheses. ABC. ")p)->xyz. 4;. are required. tightly than the cast. prohibited unconditionally for what clearly visible nicely. purpose. =. since the -> operator more binds idea is not that such code should be but that any such constructs should be they are; the cast operator serves this. The. Exactly intent is present in the pointer the same conversion By using a cast warning. the programmer can eliminate operator, is then explicitly intentional, and the warning; the conversion of sloppy coding. not simply the result In addition, there is a more important Although many C programs reason for the warning. make be the implicit assumption that pointers may of all types types)" and in stored retrieved int variables (or other pointer makes without no the language itself of guarantee difficulty, this. On word-addressed machines, in fact, such conversions will the warning message not always work properly; provides a gentle (and non-fatal) reminder of this fact. oí union is used the warning generated when a structure function without the address-of argument is operator intendeCi to remind programmers that this compiler does not allow be such an a passed function aggregate to to -- only pointers to objects.. Finally, as a. Arbitrary Limitationg Although the definition of 2.1.2. a programming language is an idealized by a number abstraction, is constrained any real implementation Thé of factors, not the least of which is practicality. Lattice compiler imposes the following arbitrary restrictions on the language accepts:. it. o. maximum size, in bytes, of any declared object is the positive largest integer which can be represented as an int. maximum This implies, for example, a size of 32767 bytes for The. 2-3.

(18) Lattice. 8086/8088. C. Compiler. Definition. Language. The l6—bit int machines. total size of all objects declared with the same storage class is also 6ubject to the same. restriction.. o. The maximum value of the constant expression defining size of a single subscript of an array is one less than pQsitive largest int (32766 for a 16-bit int).. o. The. the the. total size of the formal limited to a maximum of 256. of. formal. parameters for any function is number bytes. Thus, the maximum depends on their sizes.. parameters size. maximum. o. The. o. Macros with arguments.. o. The. maximum. string constant arguments are limited to. level. of. a. of Finclude. file. is a. 256. bytes.. maximum. nesting. number. of. 8. is 4.. limitations are impomd because of the way objects are represented internally by the compiler; our hope is that they are reasonably large enough for most real programs.. These. 2.2. Major. Language Features. material presented in this section is meant some to clarify of the language feature8 which are not always fully defined in the Kernighan and Ritchie text. These are features which depend made on" implementation decisions in the design of the compiler Those of the language definition. or on interpretations itself, features which are specifically machine dependent language are described elsewhere in this manual. The. 2.2.1. Pre-processor. Lattice. The commands. Features. compiler supports the full set of pre-processor and Most described in Kernighan Ritchie. commands implementations perform the pre-processor concurrently and analysis with lexical syntactic of the source file, because an additional compilation step can be avoided by this technique. a of the compiler incorporate Other versions separate prephase in order to reduce the size of the first phases processor of the compiler. In either case, the analysis of the precommands C is largely independent of the compiler's processor language analysis. tdefine Thus, text substitutions are not commands, any performed generally for of the pre-processor although nesting of macro definitions is possible since substituted text is always re-scanned for new #define symbols. C. exception. which is processed Dccurs for the #if command, As noted in the of differences, sizeof cannot and must apDear the expression áif expressions, These a single result ftom a line. restrictions and desire simple, to keep #if expressions because the prehas no information about the size of declared processor generally An. differently., be used in entirely on. 2-4. list.

(19) 8086/8088. Lattice. Compiler. C. Language. Definition. a symbol One other objects. clarification should be noted: defined in a expression which has not been in an appears command, a value as of zero had been is interpreted tdefine and usage permits seems with #ifdef consistent This specified. Otherwise, the use of symbols which may or may not be defined. #if expressions support the full range of operations described in Section 15 of Appendix A of Kernighan and Ritchie.. if. tifit. if. has command, the 2.1.1, as in Section noted contained text must all be that the macro invocation on a single input line. Because the compiler uses a text buffer may occasionally a particularly complex macro fixed size, of this usually, however, cause a line buffer overflow condition; when in the more reference occurs than one macro error occurs and be can circumvented by placing the macros same source line, on different lines. Circular definitions such as. The. Qdefine. limitation. tdefine tdefine. A B. B A. by be detected used, the compiler if either A or B is ever will of C, more as will Like many other implementations subtle loops. compiler supports nested macro the Lattice definitions, so that if the line. tdefine is followed. later tdefine. XYZ by XYZ. definition. the new forgotten.. In other. #undef. 12. 43. takes words,. effect, but the after encountering. old. one. is. not. XYZ. To completely undefine definition (12) is restored. each The rule is that additional tundef is required. tundef before the must be matched by a corresponding. the former XYZ,. an. tdefine symbol is 2.2.2. truly "forgotten".. Arithmetic. objects. objects are supported Six types of arithmetic with pointers, these objectb compiler; along entities which can be manipulated in a C program. short or 8hort int char unsigned or unMgned long or long int. float. double. or long. by. the Lattice the represent The types are:. int. float. 2-5.

(20) Lattice. 8086/8088. C. Compiler. Note that in this implementation, a separate data type.. Definition. Language unsigned. is not. a. modifier. but. size of integers natural for the target machine (the machine which code is being generated) is indicated for by a plain int type specifier; short type will be identical to either or this on depending long, machine. the architecture of the target Although the size of all these objects is technically machinedependent, the Lattice compiler assumes the target machine has an and B-bit, that the fundamental I6-bit, or 32-bit architecture quantity is an B-bit byte. storage Only in connection with bit become important. fields does this assumption ever The. compiler follows the standard pattern for conversions between the various arithmetic "usual arithmetic the so-called types, The conversions" described in the Kernighan and Ritchie text. exception only byte-oriented to this occurs in connection with machines, where expansion of char to int uiay be avoided both and in an operacds expression are char, the target machine and logical operations. supports byte-mode arithmetic The. if. 2.2.3. Derived. objects. leading Lattice C compiler supports the standard extensions various kinds objects, including pointers, of derived to and and functions, unions. Declarations of structures arrays, be may these although complex, types not all arbitrarily declarations in a legal object. result of For example, arrays The functions returning aggregates are or functions illegal. and compiler checks for these kinds of declarations also verifies that structures or unions do not contain instances of themselves. objects which are declared as arrays cannot have an array length of zero, unless they are formal parameters or are declared extern assumed 2.2.4). (see Section to be the same All pointe,rs are with On one exception. size usually, that of a plain int --machines, pointers which point to objects word-addressed which as can to require twice appear on any byte boundary are assumed much storage as pointers to objects which must be word-aligned. The. that the size of aggregates (arrays by alignment requirements. affected For Note. structures) example, the. and. may. be. array. { struct short. i; xtl0];. char c; }. will be. occupy aligned on. 2.2.4. Storage. 40. bytes. an. even. on machines which require byte address.. short. objects. to. Classes. Declared objects are assigned by the compiler to storage offsets which are bases. storage to one of several different relative The base on assigned storage depends the explicit storage class 2-6.

(21) Lattice specified declaration, External. 8086/8088 in as. C. Language Definiticm. Compiler. the declaration, follows:. or. on. the. context. of. the. object is classified as external the extern and in its declaration, the is present keyword object is not later defined in the source file (that is not declared outside the body of any is, is Storage function without the extern keyword). for external items because they are not allocated and be assumed must to exist in some other file, a during included the linking process that builds set of object modules into a load module.. if. An. it. Static. is classified as static the static object is is present in its declaration keyword or without an declared outside the body of any function is Storage specifier. explicit storage class items of in the data section allocated for static object module; the are all such locations expression unless an initializer initialized to zero declaration 2.2.6). is included in the (see Section declared outside the body of any Static items function without the static keyword are visible in defined. other files, that is, they are externally as Note that string constants are allocated static and items, are treated as unnamed static arrays of char.. Auto. object is classified as auto the auto keyword is declared is present in its declaration, or inside without an explicit the body of any function storage class specifier (it is illegal to declare an object the body of a function). auto outside for auto items using Storage is presumably allocated a during execution of the function stack mechanism in'which they are defined.. Formal. An. if. An. if. An. if it. if it. is a formal is classified as formal of the functions in the source to one 18 presumably allocated formal for Storage items when a function call is made during execution of the program. object parameter. if it. file.. no assumption the phase of the compiler makes Note that declarator. tbe validity of the reqister class about storage but storage is Items which are declared register are so flagged, against either the auto or the formal allocated for them anyway The implementation of register base. storage is machinedependent and may not be supported in some cases.. first. option is used, the implicit Note also that the x compile-time storage class for items declared outside the body of any function changes from static to extern. This allows a single header file used When for all external data definitions. the main to be. if. 2-7.

(22) Lattice. 8086/8088. C. Compiler. Language. Definition. and so is compiled, the x option is not used, the function various objects are defined and made externally visible; when the functions the x option other causes the same are compiled as declarations defined references to be interpreted to objects elsewhere.. 2.2.5. Scope. of. Identifiers. almost exactly to the scope rules Lattice compiler conforms in Appendix A of the Kernighan and, Ritchie discussed text (pp. The 205-206). in connection with structure only exception arises member and names, 2.1) union where (as noted in Section the names for each structcre compiler keeps separate lists of member this means that additional classes of nm-conflicting or union; Two identifiers occur for the various structures and unions. points are worth clarifying. additional The. when identifiers are declared at the beginning of a internal (other than the first block to a function statement any following the fanction name), storage for block immediately base against the current of auto auto items declared is allocated When the next available the statement block terminates, storage. preceding those offset is reset to its value auto storage be may reused by later Thus, that declarations. stQrage space and Rather than generate explicit allocate local declarations. operations, the compiler dealLcxmte to uses this mechanism the function; the compute the totsl auto storage required by is called. allocated whenever the function resulting storage isfunctions more storage With this scheme, will allocate possibly needed be inner (in the event that those statement than will need run-time dynamic but the for blocks are not executed), allocation witjÁn the function is avoided.. First,. an is Second, when identifier with a previous declaration redefined locally in a statement block with the extern storage in the the previous definition is superseded class specifier, with fashion but the compiler also verifies compatibility normal done This is any preceding extern definitions of the same name. in accordance with the principle expressr"d in the text, namely which refer to the same that all functions in a given program Within a source external identifier refer to the same object. declarations the compiler also verifies that all external file, The in tjLE!e. point is that in this particular case agree -an where a local block redefines extern identifier uponas termination -- the does of disappear declaration not effectively item external since the compiler now has an additional the block, declarations. for which must verify equivalent. it. 2.2.6. IrÜtialiµers. objects which Section 2.2.4) begins program used to define. 2-8. in are of the static storage class (as defined the are guaranteed to contain binary zeros when expression is execution, unless an initializer The Lattice compiler a different initial value..

(23) 8086/8088. Lattice. C. Compiler. Language. Definition. in expressions described the full range of initializer supports and the initialization of Ritchie, but Kernighan restricts be An arithmetic object may somewhat. pointers initialized with that evaluates constant which, an expression to an arithmetic is converted to that of the target type, not of the appropriate object.. if. used is more expression to initialize a pointer restricted: evaluate to the int constant zero or to a pointer OE exactly a pointer yielding the same type as the include pointer being initialized. This pointer expression can object, declared static or extern the address of a previously a but plus or minus an int constant, cannot incorporate cast conversion) because pointer conversions (type operator, are not a cast evaluated operator at compile time (exception: can be used a variable" This but not on name). on an makes int constant impossible to an to initialize a pointer restriction an is allowed to be used on unless the & operator array array & is name, name without the preceding because the array automatically converted to a pointer element of the to the as noted in Section 2.1, the Lattice Accordingly, array. name so that the & operator on an compiler accepts array declarations such as The. it must expression. it. it. first. int can. be. being must. a[5]0. ("pa) [5]. =. &a;. a pointer to a structure (or union) is Note that used name the structure to generate an address preceded by the & operator.. made.. initialized, be. if. be may complex objects (arrays and structures) initialized expressions, bracketed, comma-separated lists of initializer an with arithmetic each expression corresponding to or pointer A closing be used to element of the aggregate. brace can A and see Appendix of Kernighan Ritchie terminate the early; be may under this for examples. Unions not initialized implementation, containing although the first part of a structure be a may the expression ends before union initialized A character reaching the union. array may be initialized with a need be enclosed in braces; this is the not string constant which braces around the only exception of to the rule requiring initializers for an aggregate. More by. list. if. list. list. expressions for auto objects can only be applied Initializer and arithmetic types (not to aggregates), or pointer entirely equivalent to assignment statements. simple 2.2.7. Expression. to are. Evaluation. by of the standard operators the Lattice are supported compiler, in the standard order of precedence (see p. 49 of and Kernighan Ritchie). Expressions are evaluated using. an parsing technique which reduces complex precedence operator 'to a sequence of unary and expressions binary operations involving Operations involving only at most two operands.. All. 2-9.

(24) Lattice. 8086/8088. Compiler. C. Language. Definition. operands (including constant are floating point constants) by evaluated the compiler immediately, but no special effort is re-order operands in order to group constants. Thus, to expressions such as made. C. -. 'A'. +. 'a'. must be parenthesized constant part: C. +. ('a' -. so. that. the compiler. can. evaluate. the. 'A'). least at If intermediate. one operand in an operation is not constant, the by a expression is represented result temporary known The location, as a temporary. storage temporary is then an into" the larger expression and becomes "plugged operand of binary or unary operation; another the process continues until has The the entire expression been evaluated. lifetimes of and temporaries assignment locations to storage their are internal determined by a subroutine to the first phase of the which recognizes generated temporaries compiler, identically recomputation within a straight-line block of code and eliminates common sub-expressions equivalent results. of Thus, are and For evaluated example, in the recognized only once. statement. a[i+l]. b{i+l); i+l will. =. used be evaluated the expression for once and operations. Expressions which produce a result subscripting used and as is never which have no side effects, such. both that. i+j; are discarded. by. this. same. subroutine.. analysis of code examined by the temporary Within the block subroutine, operations which produce a temporary result are noted be remembered and may so operations equivalent that later Two conditions (other than function as noted above. deleted, have undetermined side effects) cause the calls, which may and no longer check for the subroutine to discard an operation (I) either operation of equivalent its operands later: (2) or appears directly as a result of a subsequent operation; a through a operation defines an indirect (i.e., subsequent one as of the for the same type of object pointer) result based The on the is original operands. latter condition compiler's assumption that pointers to are always used to refer an so for example, the correct that, type of target object, made using an int pointer only objects of type assignment is int be changed. Only when the programmer indulges in tjLEe can using a pointer punning to inspect an object as were a is this assumption invalid, and is hard to different -- type -sub-expression detection a case where the common conceive ofprob"1em will Such practice. with this somewhat dubious cause a. if. if. if. if it it. 2-ID.

(25) 8086/8088. Lattice. inspections modules in. any. C. Language. Compiler. are generally case.. better. left. to. assembly. Definition language. detection, which the exception of this common sub-expression previous, equivalent a operation with an one, replace they expressions ate evaluated in strict left-to-right order as of course, where that is prevented by except, are encountered, make operator precedence or parentheses. It is best not to since any the about the order of evaluation, assumptions, however, phase code the sequence free to re-order is generally generation The most exceptions important operations. of many are the the 'for which The logical OR (||) and logical AND (&&) operators, evaluation. guarantees left-to-right language definition code on expression effects generation phase may have other assumptions about pointer some favorable evaluation; usually, though these can be shut off by a compileassignments are made, Check section of this manual for the implementation time option. with may. full details. 2.2.8. Control. Flow. and the Lat"tice a rich offers set of statement flow constructs, Some minor the full complement of them. compiler supports points of clarification are noted here. First of all, the contain (I) at least compiler does verify that switch statements and (3) not more one (2) no duplicate case values; case entry; the first phase of the In addition, than one "default" entry. involving recognizes certain compiler statement flow constructs and may discard certain portions of code constant test values, (Even ultimately discarded are fully those portions accordingly. eliminated.) analyzed, lexically and syntactically, before being only the code for statement has a constant test value, If an is retained; clause (the then or else portion) the appropriate while, do, and for statements with. zero test values are entirely discarded. C. if. makes a special phase generally code generation effort to flow. In particular, generate sequences for control efficient is kept to a minimum of branch instructions the size and number and by switch analysis of the flow within a function, extensive of to determine the most efficient statements are analyzed Check the machine language constructs. possible several section of this manual for the details regarding impleñentation this particular code generator. The. 2.3. Comparison. to the Kernighan. &. Ritchie. "C. Reference. Manual". language precise -most definition of A the C programming of the Kernighan and Ritchie generally available is in Appendix C. section This Manual. Reference text, whichin isthe entitled of saíne order defined in the text, a series presents, amendments to that 'manual; this C commentary or annotations language of the Lattice explicitly states any deviations Because described. implementation from the features this and Ritchie implementation is close to the Kernighan very The. 2-ll.

(26) 8086/8088. Lattice standard, sections can. Compiler. Language. of the sections appjY exactly as Any section riot be commented upon. to be fully valid for the language compiler. many. will assumed. be. Lattice CRM. C. C. 2.1. Definition. written; these not listed here accepted by the. Colnment6. Lattice. allows comments that is,.each to be nested, be matched by a corresponding before the */ This feature makes out" easy to "comment The c of code which themselves contain comments. large sections in compile-time option forces the compiler to process comments non-nesting mode. the standard, The. compiler. encountered must /" comment terminates.. 2.4.3. Character. it. constant8. extensions constants ate provided. to character First, more be enclosed may in single quotes; the result than one character be and may int or long, depending on the number of characters, Second, the first character its value is machine-dependent. following the next one the backslash in an escape sequence is x, as a hexadecimal value. Thus, or two digits are interpreted Two. if. '\xf9' generates CRM. a. character. with. the value. 0XF9.. 2.5 Strings. identically wíitten string Lattice compiler recognizes (Note that constants and oñiY generates one copy of the string. used strings to initialize char arrays -- not char * -- are not generated, because they are really just shorthand for a actually The same \X of single-character constants.) comma-separated be can employed in strings, where convention described above more useful. is generally The. list. CRM See. it. 2.6 Hardware characteristics the. implementation. section. of. this. manual. for. hardware. characteristics. CRt'l. 7.1 primary. expressions. Lattice and compiler always enforces the rules for the use of unions for the simple reason that cannot structures names otherwise determine which is intended. list of member a Recall separate from Section 2.1 that the compiler maintains for each type of structure Therefore, of members or union. list primary be must expression preceding the . or -> operator the immediately recognizable as a structure to a structure or pointer of a specific type. The. it. 2-12.

(27) Lattice CRM. 8086/8088. C. Compiler. Language. Definition. 7.2 Unary operators. to an requirement that the & operator can only be applied is relaxed slightly to allow application to an array" name lvalue (wtÜch is not considered an lvalue). Note that the meaning of is a pointer such a construct to the array itself, which is'quite The to the first element of the array. different from a pointer difference between a pointer to an array and to an array's first when in an is used the pointer is only important element expression with an int offset, because the offset must be sealed by the pointer (multiplied) the size of the object to which points. In this case the target object size is the size of the the rather than the size of a single element, whole array, pointer points to the array as a whole. The. if. CRPf. 7.6 Relational. operators. the right-hand of different types are compared, pointers operand; operand is converted to the type of the left-hand and one of the integral types causes a comparison of a pointer Both of these are conversion type. of the integer to the pointer value and operations of questionable are certainly machinedependent.. When. CRM. 7.7 Equality. The. same. CRM. 8.1 Storage. operators. conversions. noted above are applied.. class-specifiers. omitted from the storage class-specifier, This is function, is taken to be extern. in fact (as the not plainly inaccurate; 11.2), the presence or absence of extern whether an object is being defined or is critical to determining As in Section 2.2.4 of this document, noted referenced. in some then the declared object either exists extern is ptesent, same no storage other file; file or is defined later in the declared object is being specifier is present, then the class and the static defined will be visible in other files. specifier is present, Thethe object is also defined but is not made externally only exception to these rules occurs for visible. statement body functions, where is the presence of a defining is being defined. that determines whether the function The. text. states. if. that. a declaration outside a somewhat misleading, oUt in CRM text points. if. if. if If. it. Lattice compiler outside declarations Declarations option. are not affected.. The. CRM The. 8.5 Structure. and. be for forced to assume extern all by means of the x compile time function which explicitly specify static or extern can. a. union declarations. members quite compiler treats the names of structure and The names of members from Kernighan and Ritchie. not conflict with each other or with the identifiers used. Lattice. differently do tags. 2-13.

(28) Lattice. 8086/8088. Compiler. C. Language. DefinitÁon. and ordinary variables. Both structure union tags are in the so class of names, that the same tag cannot be used for both and A a is a union. of members separate structure name may maintained for each structure; thus, a member not appear used be in twice in a particular structure, but the same name may within several different structures the same scope.. for. same. list. CRM. 8.7. Type. Although. name8. a. specifier,. structure. union. or. refer to it definitions cannot must. structure the sequence. {. (struct is not permitted,. struct. int. may appear known an already be wade inside a. high,. }. *). low;. };. low;. in. a type name that tag, is, Thus, type name.. x. but HL. O O 0. HL. (struct. {. int "). high,. x. is acceptable. CRM. l0.l. function. External. definitions. declared noted in the text, formal parameters float are as double; interpreted actually similarly, formals áeclared char as Lattice compiler co.nsistency, the For or short ate read int. a function declared applies the same rules to functions: to return float is assumed to return double, and char or short functions to return int. AS. CRM. 10.2 External. data. definitions. data Lattice compiler applies a simple isrule to external actual the declarations: the keyword extern present, storage will be allocated elsewhere, and the declaration as anis a reference Otherwise, simply is interpreted to actual which allocates storage (unless the x option definition has CRM comments on 8.1). been used; see the The. if. it.. CRM. 12.3 Condi-tional. compilation. 2.2.1 this of noted in Section may expression following not contain #if must appear on a single input line. As. Crm. it. document, the sizeof. the constant and operator,. 12.4 Line control. need Although the filename for #line is denoted as identifier, The of C identifiers. not conform to the characteristics supplied; the compiler takes whatever string of characters is requirement for the filename is only that cannot lexical contain any white space.. it. it. 2-14.

(29) Lattice CRM. 8086/8088. 14.1 Structures. C. Compiler and. Language. Definition. unions. escape from typing rules described in the text is explicitly by the Lattice compiler. In a reference not allowed to a the name on the right must be a member structure or union member, of the aggregate named or pointed to by the expression of the This implementation, however, does not attempt to enforce left. any on reference to union members, such as requiring restrictions member before allowing a value to be assigned to a particular to be examined via that member. The. it. Future versions of the compiler may support structure assignment, the but value of other operations passing (such as aggregates them seems from functions) questionable. directly to or returning. 2~15.

(30) Lattice. 8086/8088. Section Portable. 3:. Library. C. portable. Compiler. Library. Functions. Functions. In order to provide real portability, a C programming environment ñOit way only a wellmust provide -- inbuta machine-independent -The a library of useful as well. defined language functions C compiler provided with Lattice portable the attempts to library Álthough not all of the features of this requirement. by these functions can be implemented on every system supported be able to must provide basic the compiler, the systems all and allocation, functions of memory ch.3racter file input/output, manipulation; otherwise, string the compiler itself could not be An important benefit implemented. side of presenting the functions from a machine-independent viewpoint is that helps the programmer think of them as such.. fulfill. it. descriptions in this presented to the function referring remember seccion, that the compiler assumes that a function will an otherwise. is explicitly declared return int value unless be Any must any function which other kind of value returns usage in advance of its first as declared that kind of function in the same file.. when. it. 3.1. Memory. Allocation. Functions. standard library provides memory allocation capabilities at The higher level functions several different levels. call the interfaces but provide easier lower levels to perform the work, The amount in exchange for the extra overhead. actual of memory on the size available is system-dependent and usually depends of made most the program. available' for In systems the memory by used dynamic allocation is the same memorjj' these functions for and the run-time stack (used for function auto variables). calls number On a default these systems of bytes is reserved for the and is used by the remainder of the memory the memory stack, functions. In order to allow programs to adjust the allocation amount of memory reserved for the stack (and thus the amount available dynamic allocation), the main for program usually the default stack size; supports a special =n option to override Check a program may altermatively, define the size internally. manual The implementation for details. the section of the user is. cautioned that o,n. many systems there ,i,s, no, check aqainst the and o_f, overrunninq destroying portions stack its allotted size the memory pooI. The. All" of the memory functions allocation return of type char *, but is guaranteed to be properly any object.. a. pointer aligned. which is to store. 3-I.

(31) Lattice 3.1.1. 8086/8088 Level. 3. C. Memory. Compiler. portable. Library. Functions. Allocation. functions described in this section provide a ÚNIX-compatible memory-allocation of memory obtained may br facility. The blocks released in any order, but it is an error to release somethinq by thcsc> Recause one of these functions. not obtained calling keep use overhead locations of allocation functions track to The sizes, the free function does not require a size auíument. however, decrease the efficiency with which thesr· overhead does, use memory. functions the available If many small allocmtinn': memory the available are requested, will be more efficié"ntly 2 used the level functions instead. are utilized The. if. 3~ 2. —.

(32) Lattice. 8086/8088. C. Compiler. Portable. Library. Functions. name. malloc. UNIX-compatible. --. memory. allocation. SYNOPSIS p. =. malloc(nbytes);. char *p; unsigned. block nbytes;. number. pointer of bytes. requested. DESCRIPTION. Allocates. in a way that is compatible with block of memory primary difference between malloc and getmem is a structure that the former allocates at the front of each can This block. result in very inefficient use of memory when making many small allocation requests. UNIX.. a. The. returns p. = =. null pointerif. not enough space available to block of nbytes of memory. otherwise. CAUTIONS. Return value must be checked for NULL. declared char " and a cast operator as pointer to some other kind of object, be. The used. in:. function should a defining. if. char *mal1oc();. int "pi; 0 D O pi = (int. *)malloc(N);. 3-3.

(33) 8086/8088. Lattice. C. Compiler. Portable. Library. Functions. NAME. calloc. allocate. --. memory. and. clear. SYNOPSIS p. =. calloc(ne1tf. char *p; unsigned unsigned. eltsiz); block. ne.lt;. eltsiz;. pointer of elements element size in bytes number. and clears (sets to all zeros) a block of memory. Allocates by The the product of the two size of the block is specified convenient this calling technique is obviously parameters; Typically, the second argument is a for allocating arrays. sizeof expression. RETURNS p. = =. NULL. jr. pcñnter. not enough space available otherwise to block of memory. CAUTIONS The function should Return value must be checked for NULL. be declared a pointer defining to char * and a cast used as some in: other kind of object,. if. "calloc(); struct buffer "pb;. char. D U e pb =. 3-4. (struct. buffer. ")calloc(4, sizeof(struct buffer));.

(34) Lattice. 8086/8088. C. Compiler. Library. Portable. Functions. name. free. UNIX-compatible. --. release. memory. function. SYNOPSIS. ret. free(cp);. =. return code block pointer. int ret;. char *cp; DESCRIPTION. by allocated that was previously Releases a block of memory The is pointer should be char " and malloc or calloc. checked for validity; that is, verified to be an element of the memory pool. RETURNS. ret. 0. = =. -I. if if. successful invalid block. pointer. cautions Remember. to cast. the pointer. back. to char. "u. as. in:. char "malloc();. int "pi; * * 0 = (int. pi. P P. if. *. *) malloc(N);. (free((char. *)pi). !=. D). {. .... error. .... }. 3-5.

(35) P. Lattice 3.1.2. 8086/8088 Level. 2. C. Memory. Compiler. portable. Library. Functions. AlloCation. The arid functions described in this section provide an efficient memory 3 convenient allocation Like the level capability. and functions, allocation de-allocation requests may be made in and by any order, is an error to free memory not obtained The means of one of these functions. must retain both the caller pointer and the size of the block foF use when is freed; length may lead to wasted memory failure to providecan the correct when functions length (the detect an incorrect is too An additional large, but not when is too small). convenience sizmem by be used function, is provided the which can to determine the total amount of memory available.. it. it. it. it. 2 functions level maintain a linked of the blocks of released by calls to rlsmem, called the free space list. by memory Initially, this list is null, and getmem acquires As sbrk. blocks are calling the level l memory allocator when a released by the program, the free space list isis created; block adjacent freed, is to one already on the combined with any adjacent blocks. Thus, the size of the largest be smaller may than the total amount free available of block due memory, to breakage. The. memory. list. list. 3-6. it.

(36) Lattice. 8086/8088. Compiler. C. Portable. Library. Functions. NAME. getml. getmem,. --. get. a. memory. block. SYNOPSIS p p. = =. getmem(nbytes); getml (lnbytes);. char "p; unsigned nbytes; long lnbytes;. block. pointer of bytes requested long number of bytes requested. number. DESCRIPTION. Gets a block of memory from the free memory pool. the size is not pool is empty or a block of the requested memory more is obtained via the level I function available, sbrk.. If. RETURNS p. = =. null. if. pointer. not enough to memory. space available block otherwise. CAUTIONS. Return value must be checked for NULL. declared char * and a cast used some as in: other kind of object,. if. be. The. defining. function should a pointer to. char *getmem(); struct xyz "px; O 0 O px = (struct. xyz ")getmem(sizeof(struct. XYZ));. 3-7.

(37) Lattice. 8086/8088. Compiler. C. Portable. Library. Functions. name. rlsmem,. rlsml. --. release. a. memory. block. synopsis ret ret. = =. rlsmem(cp, nbytes); rlsml(cp, lnbytes);. int ret;. char *cp; unsigned nbytes; long lnbytes;. return code block pointer size of block size of block. freed. to. be. as. long. integer. description the memory block by placing the new block is adjacent to are combined.. Releases. list.. If. they. it a. on. a. block. free block the. on. list,. returns ret. = =. 0. -I. if successful block is not if supplied getml or if it overlaps list. one. obtained by getmem of the blocks on. or the. cautions value should Return size is not supplied,. 3-8. checked for the block may. be. etror. not be. If. freed. the correct proDer}y..

(38) Lattice. 8086/8088. C. Compiler. Portable. Lib'rary. Functions. NAME. allmem,. bldmem. --. allocate. level. 2 memory. pool. SYNOPSIS. ret ret. = =. allmem(); bldmem(n);. int ret; int n;. code. return. maximum. of I kilobyte. number. blocks. DESCRIPTION The. bldmem function uses the level up allocate to n I kilobyte blocks of then all availabTe memory is allocated. The. alhnem function. Subsequent. getmem. merely and. getml. calls bldmem calls memory will. pool. this memory All of the a call to getmem following calls rstmem the function. described. can. below.. 1 function iíiemory.. with. n. If. sbrk is. to 0,. n. set to. CL. make be. allocations from by getmem allocated by a freed call to. RETURNS. ret. = =. -I. 0. if first sbrk fails if successful. CAUTIONS. Should program.. be. called. only. once. during. the. lifetime. of. the. 3-9.

(39) Lattice. 8086/8088. Compiler. C. portable. Library. Functions. NAME sizmem. get. --. memory. pool size. SYNOPSIS. bytes. =. sizmem(); number. long bytes;. of bytes. DESCRIPTION. of unallocated bytes in the memory pool and getmem getml. Note that getml by dynamically expand the pool calling sbrk whenever bya the value returned Therefore, request cannot be honored. sizmem how much memory indicate is does not necessarily used available. actually afterbe calling a.llmem, however, If pool size will returned. the actual memory Returns used. the. by. number. getmern. and. RETURNS. bytes. =. (long). number. of bytes. in. mermry. pool. CAUTIONS. Note that this function declared long before. it. 3-ID. returns is used.. a. long integer,. and. must. be.

(40) Lattice. 8086/8088. C. Compiler. Portable. Library. Functions. NAME rstmem. --. reset. memory. pool. SYNOPSIS. rstmem(); DESCRIPTION. the ,l,ey.e,l. ? memory pool to its initial state. All by and made allocated getml to getmem after calls by was allmem called is released allocated rstmem; memory before allmem was called is not affected. This function makes make number a certain possible to of initial sbrk, and getmem, then to initialize a memory or getml calls, pool Any made by calling allmem. allocations after the call to by allmem are freed rstmem, but the preceding sbrk or getmem calls are not affected. Resets. memory. it. CAUTIONS. This. any function cannot be used files have been opened the immediately preceding allmem call for access using because these functions any of the leve} 2 I/O functions, opened buffers. Files shÓuld be to allocate use getmem allrnem before the call to avoid this problem.. after. if. 3-ll.

(41) Lattice 3.1.3. 8086/8088 Level. l. C. Memory. Compiler. portable. Library. Functions. Allocation. memory defined level of two functions at the lowest allocation which perform the basic operations are primitives needed they are used to implement a more sophisticated facility; by the level 2 functions for that purpose. sbrk treats the total amount as a single available of memory block, from which portions a creating of a specific size may be allocated at the low end, new block of smaller size. rbrk merely resets the block back to The "break point" mentioned here shouZd not its original size. be used confused with the breakpoint in debugging; concerjt this term simply refers to the address of the low end of the block of by sbrk. memory manipulated The. 3-12.

(42) 8086/8088. Lattice. Compiler. C. Portable. Library. Functions. NAME. sbrk,. lsbrk. set. --. memory. break point. SYNOPSIS p p. = =. sbrk(nbytes); lsbrk(lnbytes);. char *p; unsigned nbytes; long In bytes;. points. address to low allocated of bytes to be allocated long number of bytes to be allocated. number. DESCRIPTION. Allocates possible.. block. of memory of the requested size, UNIX memory functions form the basic allocator. first time one of them is called, will Then allocate memory. the largest available block of high end low the requested number of bytes is subtracted from the of the block for use by the caller. a. if. These The. it. returns p p. = = =. cannot fulfilled -l if request request cannot fulfilled if pointer to low address of block 0. be be. (sbrk only) (lsbrk only) successful. if. CAUTIONS. consistency with the UNIX function, sbrk returns the request, although the rest cannot of satisfy NULL. memory allocators Both functions return should * and used a cast declared a char defining pointer some other kind of object. For. -l theif. it. if. be. to. 3-13.

(43) Lattice. 8086/8088. C. Compiler. portable. Library. Functions. NAME. rbrk. --. reset. memory. break point. SYNOPSIS. rbrk(); DESCRIPTION. the This space block. Resets. point.. memory. break point to returns. effectively. its all. original. memory. to. startingthe. free. CAUTIONS. Like are. 3-14. if. any cannot be used rstmem above, this function files and being accessed using the .l.eye.l. E I/O functions.. open.

(44) Lattice 3.2. 8086/8088 I/O. and. System. C. Compiler. Portable. Library. Functions. Functions. standard library provides 1,/0 functions at several different levels, with single character 2ÉÉ and put functions and formatted and l/O at the highest levels, direct byte stream T/Q functions The the lowest levels. major system dependency at arises in where some connection with text files, certain systems perform accommodate translations the particular to text file usc"d representation in the local environment. Although the translation is generally transparent at the higher levels, I/O at the lowest levels, binary data, I/O involving must particularly be Check cjf the translation. aware the implementation section of manual for the details appropriate to a particular sYstem. this The. Three general classes of I/O functions are provided. First, the 2 functions level define a buffered text file interface which macros implements as the single character I/O functions rather Second, than function calls. the level l functions define a byte stream-oriented interface, primarily useful for manipulation file most of disk files, of the same functions though are applicable to devices (such as the user's console) as well. FinaZZy, since most one common of the is with the user's console, I/O interfaces T/O a special set of functions allows single character directly as well as formatted and string I/O. to the user's terminal, discussed in this section are concerned with system functions Additional system functions program exit. are described in the implementation section of the manual. The. 3.2.1. Level. 2. I/O Functions. and. Macros. a buffered These functions provide a interface using special by manipulated internally structure, the functions, to which a pointer called the file pointer is defined. This structure is most defined in the standard I/O header file (called stdio.h on be must (by means which systems) generally included of a #include .l.eye,l. 2 features statement) in the source file where are being The used spécíÉy"the used. pointer is to file be file upon which Some operations performed. functions require a file are to such as pointer,. FILE "fp; to be explicitly included in the calling sequence; others imply a specific In particular, the file pointers stdin file pointer. and by and stdout the use of several functions are implied used gYgtems these that on most macros; are sci commonly files they automatically before the main function of a are opened Other file pointers must be declared program begins execution. by the programmer and initialized by calls to the topen function. The. functions with text are designed to work primarily uses usual C convention for line termination a single end character, the newline indicate a the to of line. (\n), environments use a many Unfortunately, operating multiple. files.. level. ,2.. The. 3-15.

(45) Lattice. 8086/8088. C. Compiler. Portable. Library. Functions. character sequence -- usually carriage return/line feed, but occdsionally In order to allow all even more exotic delimiters. C the Lattice programs to work with text files in the same way, functions the standard newline convention support but may -mode on a text depending the system so translation -- perform end-of-line that sequences will conformand to local conventions. This but may transparent translation is usually beneficial Normally, cause problems when working with binary files. all the level 2 functions in the are opened files accessed through mode, may translated but the override programmer this text, by ordefining mode location the external. int. _fmode. =. 0X8000;. in one of im functions in the program (this statement mustbe the body of the function in order appear outside to itself The fmode an considered external value is at definition). 1 when the" open passed to the level function is or creat file — opened mode; opened. in the text (jx8000, zero, the file is mode. is opened the in the binary, Note or untranslated fmodé and is defined as above, the stdin, that stdout, stderr áZsO be opened in the files opened for the main function will fmode can be binary mode. this is undesirable, initialized and Gx8000 before"specific with then set to fopen calls are zero made; this way, in in different different files may be opened manual modes. Check the implementatior: section of this for more modes. information about the file access. file if. If. if. If. actual I/O operations are petformed by the level 2 functions through calls to the level l L/O functions described in the next The section. normal moU of buffering, designed to supDort sequential operations, performs read and write functions in 512byte blocks. The. Normally. the. ,l.ey.e_l.. 2 functions acquire buffers via the level the file is on a device other than 3 disk. setbuf function allows a private buffer assumes This function attached. that the buffer is to be the size, which is defined via the BUFSIZ in standard constant stdio.h. If formodesome reason operating the level 2 I/O functionsbe can in the buffered is not desirable, the setnbf function is done automatically called. This for non-disk files or setbuf is called with a NULL buffer pointer.. memory. 2. allocator unless Alternatively, the. if. cjf some below, In the descriptions the function calls are The implemented as macros; actually these are noted explicitly. be aware the should cf is the distinction reason programmer and may, because most macros involve the conditional operator more conditions, under certain evaluate an argument expression This can cause unexpected results than once. that expression involves side effects, such as increment or decrement operators or function calls.. if. 3-16.

(46) Lattice. 8086/8088. Compiler. C. Library. Portable. Functions. NAME a. buffered. fopen(name,. mode);. fopen. --. open. file. SYNOPSIS. fp. =. FILE "fp; char "name; char "mode;. file file. pointer. for. specified. name mode. file. access. DESCRIPTION mode a for buffered access; the translated is the file mode as default but may be overridden described in the The introduction NULL-terminated to this section. string which specifies the filename must conform to local file The as a naming conventions. access mode is also specified and be one may of the following: string,. Opens. to to to r+ to w+ to a+ to r. w a. read write. a. append. update create append. a. file file a file a file (read and write) a file for update to and update a file to. The. mode character must be specified in lower case. option adds to the end of an existing or creates file, the w option discards any data in the file, one; On most systems, no more exists. already than 16 and (including stdin, stdout, stderr, those are for main) can be opened using fopen.. if. When may modes,. file. end. The a. a new. iffilesit. opened. file is opened for update, both reading and writing performed on the file pointer. In order to switch an fseek or rewind must be executed. Opening the append be forces all data to written to to the current of file, regardless of previous seeks. a be. RETURNS. "fp. = =. NULL. file. if. error pointer for. specified. file. if. successful. CAUTIONS The. return code must be checked for NULL; the error return be generated mode an was invalid specified the or be created, or too many files file was not found, could not were already open. may. if. if. 3-17.

Referenzen

ÄHNLICHE DOKUMENTE

Der Kellerspeicher hat folgende Methoden: push kellert eine Zahl ein, pop kellert eine Zahl aus, size liefert die Anzahl der Zahlen und iterator liefert einen Iterator mit dem

Implementieren Sie eine FIFO-Warteschlange (First-in-first-out) für Zeichen, einmal mit einem Array in der Klasse ArrayQueue (zyklischer Puffer, Array mit fixer Größe) und einmal

Implementieren Sie einen Kellerspeicher für Objekte, einmal mit einem Array in der Klasse ArrayStack und einmal als verkettete Liste in der Klasse LinkedListStack.. Die

Terminal A uses the DCP's User TELNET implementation to communicate with the remote host across the TCPjIP network.. The remote host provides

Doppelt verkettete Listen bestehen aus Listenzellen mit zwei Zeigern. • Ein Zeiger prev auf die

verschachtelten Prozeduren m¨ ussen viele Zugriffslinks verfolgt werden. Abhilfe: Displays

• Maintaining connectivity to legacy IPv4 devices/networks during the transition to IPv6-only deployments..

ourStack.push(&#34;Hallo&#34;);.. Dann testen wir, ob eine Exception geworfen wird, wenn wir versuchen, eine Element aus einem leeren Stack zu entnehmen...