From Wikipedia, the free encyclopedia
In computer programming and software development, debugging is the process of finding and resolving bugs (defects or problems that prevent correct operation) within computer programs, software, or systems.
Debugging tactics can involve interactive debugging, control flow analysis, unit testing, integration testing, log file analysis, monitoring at the application or system level, memory dumps, and profiling. Many programming languages and software development tools also offer programs to aid in debugging, known as debuggers.
Etymology[edit]
The terms «bug» and «debugging» are popularly attributed to Admiral Grace Hopper in the 1940s.[1] While she was working on a Mark II computer at Harvard University, her associates discovered a moth stuck in a relay and thereby impeding operation, whereupon she remarked that they were «debugging» the system. However, the term «bug», in the sense of «technical error», dates back at least to 1878 and Thomas Edison who describes the «little faults and difficulties» of mechanical engineering as «Bugs».
Similarly, the term «debugging» seems to have been used as a term in aeronautics before entering the world of computers. In an interview Grace Hopper remarked that she was not coining the term.[citation needed] The moth fit the already existing terminology, so it was saved. A letter from J. Robert Oppenheimer (director of the WWII atomic bomb Manhattan Project at Los Alamos, New Mexico) used the term in a letter to Dr. Ernest Lawrence at UC Berkeley, dated October 27, 1944,[2] regarding the recruitment of additional technical staff.
The Oxford English Dictionary entry for «debug» quotes the term «debugging» used in reference to airplane engine testing in a 1945 article in the Journal of the Royal Aeronautical Society. An article in «Airforce» (June 1945 p. 50) also refers to debugging, this time of aircraft cameras. Hopper’s bug was found on September 9, 1947. Computer programmers did not adopt the term until the early 1950s.
The seminal article by Gill[3] in 1951 is the earliest in-depth discussion of programming errors, but it does not use the term «bug» or «debugging».
In the ACM’s digital library, the term «debugging» is first used in three papers from 1952 ACM National Meetings.[4][5][6] Two of the three use the term in quotation marks.
By 1963 «debugging» was a common-enough term to be mentioned in passing without explanation on page 1 of the CTSS manual.[7]
Scope[edit]
As software and electronic systems have become generally more complex, the various common debugging techniques have expanded with more methods to detect anomalies, assess impact, and schedule software patches or full updates to a system. The words «anomaly» and «discrepancy» can be used, as being more neutral terms, to avoid the words «error» and «defect» or «bug» where there might be an implication that all so-called errors, defects or bugs must be fixed (at all costs). Instead, an impact assessment can be made to determine if changes to remove an anomaly (or discrepancy) would be cost-effective for the system, or perhaps a scheduled new release might render the change(s) unnecessary. Not all issues are safety-critical or mission-critical in a system. Also, it is important to avoid the situation where a change might be more upsetting to users, long-term, than living with the known problem(s) (where the «cure would be worse than the disease»). Basing decisions of the acceptability of some anomalies can avoid a culture of a «zero-defects» mandate, where people might be tempted to deny the existence of problems so that the result would appear as zero defects. Considering the collateral issues, such as the cost-versus-benefit impact assessment, then broader debugging techniques will expand to determine the frequency of anomalies (how often the same «bugs» occur) to help assess their impact to the overall system.
Tools[edit]
Debugging ranges in complexity from fixing simple errors to performing lengthy and tiresome tasks of data collection, analysis, and scheduling updates. The debugging skill of the programmer can be a major factor in the ability to debug a problem, but the difficulty of software debugging varies greatly with the complexity of the system, and also depends, to some extent, on the programming language(s) used and the available tools, such as debuggers. Debuggers are software tools which enable the programmer to monitor the execution of a program, stop it, restart it, set breakpoints, and change values in memory. The term debugger can also refer to the person who is doing the debugging.
Generally, high-level programming languages, such as Java, make debugging easier, because they have features such as exception handling and type checking that make real sources of erratic behaviour easier to spot. In programming languages such as C or assembly, bugs may cause silent problems such as memory corruption, and it is often difficult to see where the initial problem happened. In those cases, memory debugger tools may be needed.
In certain situations, general purpose software tools that are language specific in nature can be very useful. These take the form of static code analysis tools. These tools look for a very specific set of known problems, some common and some rare, within the source code, concentrating more on the semantics (e.g. data flow) rather than the syntax, as compilers and interpreters do.
Both commercial and free tools exist for various languages; some claim to be able to detect hundreds of different problems. These tools can be extremely useful when checking very large source trees, where it is impractical to do code walk-throughs. A typical example of a problem detected would be a variable dereference that occurs before the variable is assigned a value. As another example, some such tools perform strong type checking when the language does not require it. Thus, they are better at locating likely errors in code that is syntactically correct. But these tools have a reputation of false positives, where correct code is flagged as dubious. The old Unix lint program is an early example.
For debugging electronic hardware (e.g., computer hardware) as well as low-level software (e.g., BIOSes, device drivers) and firmware, instruments such as oscilloscopes, logic analyzers, or in-circuit emulators (ICEs) are often used, alone or in combination. An ICE may perform many of the typical software debugger’s tasks on low-level software and firmware.
Debugging process[edit]
The debugging process normally begins with identifying the steps to reproduce the problem. This can be a non-trivial task, particularly with parallel processes and some Heisenbugs for example. The specific user environment and usage history can also make it difficult to reproduce the problem.
After the bug is reproduced, the input of the program may need to be simplified to make it easier to debug. For example, a bug in a compiler can make it crash when parsing a large source file. However, after simplification of the test case, only few lines from the original source file can be sufficient to reproduce the same crash. Simplification may be done manually using a divide-and-conquer approach, in which the programmer attempts to remove some parts of original test case then checks if the problem still occurs. When debugging in a GUI, the programmer can try skipping some user interaction from the original problem description to check if the remaining actions are sufficient for causing the bug to occur.
After the test case is sufficiently simplified, a programmer can use a debugger tool to examine program states (values of variables, plus the call stack) and track down the origin of the problem(s). Alternatively, tracing can be used. In simple cases, tracing is just a few print statements which output the values of variables at particular points during the execution of the program.[citation needed]
Techniques[edit]
- Interactive debugging uses debugger tools which allow an program’s execution to be processed one step at a time and to be paused to inspect or alter its state. Subroutines or function calls may typically be executed at full speed and paused again upon return to their caller, or themselves single stepped, or any mixture of these options. Setpoints may be installed which permit full speed execution of code that is not suspected to be faulty, and then stop at a point that is. Putting a setpoint immediately after the end of a program loop is a convenient way to evaluate repeating code. Watchpoints are commonly available, where execution can proceed until a particular variable changes, and catchpoints which cause the debugger to stop for certain kinds of program events, such as exceptions or the loading of a shared library.
- Print debugging or tracing is the act of watching (live or recorded) trace statements, or print statements, that indicate the flow of execution of a process and the data progression. Tracing can be done with specialized tools (like with GDB’s trace) or by insertion of trace statements into the source code. The latter is sometimes called printf debugging, due to the use of the printf function in C. This kind of debugging was turned on by the command TRON in the original versions of the novice-oriented BASIC programming language. TRON stood for, «Trace On.» TRON caused the line numbers of each BASIC command line to print as the program ran.
- Activity tracing is like tracing (above), but rather than following program execution one instruction or function at a time, follows program activity based on the overall amount of time spent by the processor/CPU executing particular segments of code. This is typically presented as a fraction of the program’s execution time spent processing instructions within defined memory addresses (machine code programs) or certain program modules (high level language or compiled programs). If the program being debugged is shown to be spending an inordinate fraction of its execution time within traced areas, this could indicate misallocation of processor time caused by faulty program logic, or at least inefficient allocation of processor time that could benefit from optimization efforts.
- Remote debugging is the process of debugging a program running on a system different from the debugger. To start remote debugging, a debugger connects to a remote system over a communications link such as a local area network. The debugger can then control the execution of the program on the remote system and retrieve information about its state.
- Post-mortem debugging is debugging of the program after it has already crashed. Related techniques often include various tracing techniques like examining log files, outputting a call stack on the crash,[8] and analysis of memory dump (or core dump) of the crashed process. The dump of the process could be obtained automatically by the system (for example, when the process has terminated due to an unhandled exception), or by a programmer-inserted instruction, or manually by the interactive user.
- «Wolf fence» algorithm: Edward Gauss described this simple but very useful and now famous algorithm in a 1982 article for Communications of the ACM as follows: «There’s one wolf in Alaska; how do you find it? First build a fence down the middle of the state, wait for the wolf to howl, determine which side of the fence it is on. Repeat process on that side only, until you get to the point where you can see the wolf.»[9] This is implemented e.g. in the Git version control system as the command git bisect, which uses the above algorithm to determine which commit introduced a particular bug.
- Record and replay debugging is the technique of creating a program execution recording (e.g. using Mozilla’s free rr debugging tool; enabling reversible debugging/execution), which can be replayed and interactively debugged. Useful for remote debugging and debugging intermittent, non-determinstic, and other hard-to-reproduce defects.
- Time travel debugging is the process of stepping back in time through source code (e.g. using Undo LiveRecorder) to understand what is happening during execution of a computer program; to allow users to interact with the program; to change the history if desired and to watch how the program responds.
- Delta Debugging – a technique of automating test case simplification.[10]: p.123
- Saff Squeeze – a technique of isolating failure within the test using progressive inlining of parts of the failing test.[11][12]
- Causality tracking: There are techniques to track the cause effect chains in the computation.[13] Those techniques can be tailored for specific bugs, such as null pointer dereferences.[14]
Automatic bug fixing[edit]
Debugging for embedded systems[edit]
In contrast to the general purpose computer software design environment, a primary characteristic of embedded environments is the sheer number of different platforms available to the developers (CPU architectures, vendors, operating systems, and their variants). Embedded systems are, by definition, not general-purpose designs: they are typically developed for a single task (or small range of tasks), and the platform is chosen specifically to optimize that application. Not only does this fact make life tough for embedded system developers, it also makes debugging and testing of these systems harder as well, since different debugging tools are needed for different platforms.
Despite the challenge of heterogeneity mentioned above, some debuggers have been developed commercially as well as research prototypes. Examples of commercial solutions come from Green Hills Software,[19] Lauterbach GmbH[20] and Microchip’s MPLAB-ICD (for in-circuit debugger). Two examples of research prototype tools are Aveksha[21] and Flocklab.[22] They all leverage a functionality available on low-cost embedded processors, an On-Chip Debug Module (OCDM), whose signals are exposed through a standard JTAG interface. They are benchmarked based on how much change to the application is needed and the rate of events that they can keep up with.
In addition to the typical task of identifying bugs in the system, embedded system debugging also seeks to collect information about the operating states of the system that may then be used to analyze the system: to find ways to boost its performance or to optimize other important characteristics (e.g. energy consumption, reliability, real-time response, etc.).
Anti-debugging[edit]
Anti-debugging is «the implementation of one or more techniques within computer code that hinders attempts at reverse engineering or debugging a target process».[23] It is actively used by recognized publishers in copy-protection schemas, but is also used by malware to complicate its detection and elimination.[24] Techniques used in anti-debugging include:
- API-based: check for the existence of a debugger using system information
- Exception-based: check to see if exceptions are interfered with
- Process and thread blocks: check whether process and thread blocks have been manipulated
- Modified code: check for code modifications made by a debugger handling software breakpoints
- Hardware- and register-based: check for hardware breakpoints and CPU registers
- Timing and latency: check the time taken for the execution of instructions
- Detecting and penalizing debugger[24]
An early example of anti-debugging existed in early versions of Microsoft Word which, if a debugger was detected, produced a message that said, «The tree of evil bears bitter fruit. Now trashing program disk.», after which it caused the floppy disk drive to emit alarming noises with the intent of scaring the user away from attempting it again.[25][26]
See also[edit]
- Assertion (software development)
- Debugging pattern
- Magic debug values
- Shotgun debugging
- Software bug
- Software testing
- Time travel debugging
- Trace table
- Troubleshooting
References[edit]
- ^ «InfoWorld Oct 5, 1981». 5 October 1981. Archived from the original on September 18, 2019. Retrieved July 17, 2019.
- ^ «Archived copy». Archived from the original on 2019-11-21. Retrieved 2019-12-17.
{{cite web}}
: CS1 maint: archived copy as title (link) - ^ S. Gill, The Diagnosis of Mistakes in Programmes on the EDSAC Archived 2020-03-06 at the Wayback Machine, Proceedings of the Royal Society of London. Series A, Mathematical and Physical Sciences, Vol. 206, No. 1087 (May 22, 1951), pp. 538-554
- ^ Robert V. D. Campbell, Evolution of automatic computation Archived 2019-09-18 at the Wayback Machine, Proceedings of the 1952 ACM national meeting (Pittsburgh), p 29-32, 1952.
- ^ Alex Orden, Solution of systems of linear inequalities on a digital computer, Proceedings of the 1952 ACM national meeting (Pittsburgh), p. 91-95, 1952.
- ^ Howard B. Demuth, John B. Jackson, Edmund Klein, N. Metropolis, Walter Orvedahl, James H. Richardson, MANIAC doi=10.1145/800259.808982, Proceedings of the 1952 ACM national meeting (Toronto), p. 13-16
- ^ The Compatible Time-Sharing System Archived 2012-05-27 at the Wayback Machine, M.I.T. Press, 1963
- ^ «Postmortem Debugging». Archived from the original on 2019-12-17. Retrieved 2019-12-17.
- ^ E. J. Gauss (1982). «Pracniques: The ‘Wolf Fence’ Algorithm for Debugging». Communications of the ACM. 25 (11): 780. doi:10.1145/358690.358695. S2CID 672811.
- ^ Zeller, Andreas (2005). Why Programs Fail: A Guide to Systematic Debugging. Morgan Kaufmann. ISBN 1-55860-866-4.
- ^ «Kent Beck, Hit ’em High, Hit ’em Low: Regression Testing and the Saff Squeeze». Archived from the original on 2012-03-11.
- ^ Rainsberger, J.B. (28 March 2022). «The Saff Squeeze». The Code Whisperer. Retrieved 28 March 2022.
- ^ Zeller, Andreas (2002-11-01). «Isolating cause-effect chains from computer programs». ACM SIGSOFT Software Engineering Notes. 27 (6): 1–10. doi:10.1145/605466.605468. ISSN 0163-5948. S2CID 12098165.
- ^ Bond, Michael D.; Nethercote, Nicholas; Kent, Stephen W.; Guyer, Samuel Z.; McKinley, Kathryn S. (2007). «Tracking bad apples». Proceedings of the 22nd annual ACM SIGPLAN conference on Object oriented programming systems and applications — OOPSLA ’07. p. 405. doi:10.1145/1297027.1297057. ISBN 9781595937865. S2CID 2832749.
- ^ Rinard, Martin C. (2008). «Technical perspective Patching program errors». Communications of the ACM. 51 (12): 86. doi:10.1145/1409360.1409381. S2CID 28629846.
- ^ Harman, Mark (2010). «Automated patching techniques». Communications of the ACM. 53 (5): 108. doi:10.1145/1735223.1735248. S2CID 9729944.
- ^ Gazzola, Luca; Micucci, Daniela; Mariani, Leonardo (2019). «Automatic Software Repair: A Survey» (PDF). IEEE Transactions on Software Engineering. 45 (1): 34–67. doi:10.1109/TSE.2017.2755013. hdl:10281/184798. S2CID 57764123.
- ^ Tan, Shin Hwei; Roychoudhury, Abhik (2015). «relifix: Automated repair of software regressions». 2015 IEEE/ACM 37th IEEE International Conference on Software Engineering. IEEE. pp. 471–482. doi:10.1109/ICSE.2015.65. ISBN 978-1-4799-1934-5. S2CID 17125466.
- ^ «SuperTrace Probe hardware debugger». www.ghs.com. Archived from the original on 2017-12-01. Retrieved 2017-11-25.
- ^ «Debugger and real-time trace tools». www.lauterbach.com. Archived from the original on 2022-01-25. Retrieved 2020-06-05.
- ^ Tancreti, Matthew; Hossain, Mohammad Sajjad; Bagchi, Saurabh; Raghunathan, Vijay (2011). «Aveksha». Proceedings of the 9th ACM Conference on Embedded Networked Sensor Systems. SenSys ’11. New York, NY, USA: ACM. pp. 288–301. doi:10.1145/2070942.2070972. ISBN 9781450307185. S2CID 14769602.
- ^ Lim, Roman; Ferrari, Federico; Zimmerling, Marco; Walser, Christoph; Sommer, Philipp; Beutel, Jan (2013). «FlockLab». Proceedings of the 12th international conference on Information processing in sensor networks. IPSN ’13. New York, NY, USA: ACM. pp. 153–166. doi:10.1145/2461381.2461402. ISBN 9781450319591. S2CID 447045.
- ^ Shields, Tyler (2008-12-02). «Anti-Debugging Series – Part I». Veracode. Archived from the original on 2016-10-19. Retrieved 2009-03-17.
- ^ a b «Software Protection through Anti-Debugging Michael N Gagnon, Stephen Taylor, Anup Ghosh» (PDF). Archived from the original (PDF) on 2011-10-01. Retrieved 2010-10-25.
- ^ Ross J. Anderson (2001-03-23). Security Engineering. Wiley. p. 684. ISBN 0-471-38922-6.
- ^ «Microsoft Word for DOS 1.15». Archived from the original on 2013-05-14. Retrieved 2013-06-22.
Further reading[edit]
- Agans, David J. (2002). Debugging: The Nine Indispensable Rules for Finding Even the Most Elusive Software and Hardware Problems. AMACOM. ISBN 0-8144-7168-4.
- Blunden, Bill (2003). Software Exorcism: A Handbook for Debugging and Optimizing Legacy Code. APress. ISBN 1-59059-234-4.
- Ford, Ann R.; Teorey, Toby J. (2002). Practical Debugging in C++. Prentice Hall. ISBN 0-13-065394-2.
- Grötker, Thorsten; Holtmann, Ulrich; Keding, Holger; Wloka, Markus (2012). The Developer’s Guide to Debugging, Second Edition. Createspace. ISBN 978-1-4701-8552-7.
- Metzger, Robert C. (2003). Debugging by Thinking: A Multidisciplinary Approach. Digital Press. ISBN 1-55558-307-5.
- Myers, Glenford J (2004). The Art of Software Testing. John Wiley & Sons Inc. ISBN 0-471-04328-1.
- Robbins, John (2000). Debugging Applications. Microsoft Press. ISBN 0-7356-0886-5.
- Telles, Matthew A.; Hsieh, Yuan (2001). The Science of Debugging. The Coriolis Group. ISBN 1-57610-917-8.
- Vostokov, Dmitry (2008). Memory Dump Analysis Anthology Volume 1. OpenTask. ISBN 978-0-9558328-0-2.
- Zeller, Andreas (2009). Why Programs Fail, Second Edition: A Guide to Systematic Debugging. Morgan Kaufmann. ISBN 978-0-1237-4515-6.
- Peggy Aldrich Kidwell, Stalking the Elusive Computer Bug, IEEE Annals of the History of Computing, 1998.
External links[edit]
Wikiquote has quotations related to Debugging.
- Crash dump analysis patterns – in-depth articles on analyzing and finding bugs in crash dumps
- Learn the essentials of debugging – how to improve your debugging skills, a good article at IBM developerWorks (archived from the original on February 18, 2007)
- Plug-in Based Debugging For Embedded Systems
- Embedded Systems test and debug – about digital input generation – results of a survey about embedded system test and debug, Byte Paradigm (archived from the original on January 12, 2012)
ПОЯСНИТЕЛЬНАЯ ЗАПИСКА
Контрольная работа предназначена для контроля и оценки образовательных достижений обучающихся 10-х классов после изучения темы: «Алгоритмизация и программирование»
Задания контрольной работы по информатике состоят из теоретических вопросов по теме и обработке задачи.
В тестовых заданиях необходимо выбрать только один вариант правильного ответа.
Цели урока:
оценить уровень подготовки по изученной теме;
получить информацию о направлениях корректировки и выявление пробелов в изучении темы для дальнейшей работы над ошибками.
Характеристика структуры контрольной работы
Для проведения тестирования подготовлены два варианта с подобными заданиями. Каждый вариант контрольной работы состоит из тестовых вопросов и задачи, которую необходимо проработать и выбрать один правильный ответ.
Также к контрольной работе прилагается таблица с ответами.
Вариант 1 Дата________
Контрольная работа в формате теста
по предмету Иформатика и ИКТ
учащегося(щейся) ____класса
МОУ «Амвросиевская школа №6» Амвросиевского района ДНР
____________________________________________________________________
Тема: «Алгоритмизация и программирование»
1. Последовательность действий, допустимых для исполнителя – это…
а) программа; в) команда;
б) алгоритм; г) система команд.
2. Выявление ошибок и их устранение называется…
а) отладкой задачи; в) отладкой алгоритма;
б) отладкой исполнителя; г) отладкой программы.
3. Человек, робот, автомат, устройство, компьютер, который выполняет чьи-то команды – это…
а) помощник; в) программа;
б) исполнитель; г) приложение.
4. Алгоритмы, в которых команды выполняются последовательно друг за другом, называются:
а) линейными; в) циклическими;
б) разветвляющимися; г) вспомогательными.
5. Форма организации действий, при которой один и тот же блок выполняется несколько раз, называется…
а) следованием; в) ветвлением;
б) циклом; г) алгоритмом.
6. Совокупность всех команд, которые может выполнить конкретный исполнитель – это…
а) система программ; в) система команд;
б) система алгоритмов; г) система задач.
7. Что используют для разделения операторов друг от друга в программе Pascal?
а) запятую; в) пропуск;
б) двоеточие; г) точку с запятой.
8. Для записи вспомогательных алгоритмов в языке Паскаль используются:
а) массивы; в) процедуры и функции;
б) составные операторы; г) операторы и операнды.
9. Между формальными и фактическими параметрами следует соблюдать соответствие:
а) по типу параметров; в) по порядку следования параметров;
б) по количеству параметров; г) по всему перечисленному в пунктах а-в.
10. Величина, значение которой меняется в процессе выполнения программы, называется
а) константой; в) операндом;
б) переменной; г) служебным словом.
11. Переменные в программе на Паскале описываются в разделе:
а) TYPE; в) VAR;
б) CONST; г) USES CART.
12. Выберите оператор цикла с известным числом повторений:
а) BEGIN; в) REPEAT;
б) WHILE; г) FOR.
13. Цикл repeat until — это:
а) цикл со счетчиком; в) цикл с предусловием;
б) цикл с постусловием; г) цикл с параметром.
14. Укажите, правильную запись следующего математического выражения: y=5x2-10x+2.
а) y:= 5*sqr(x)-10*x+2; в) y:= 5*sqr(x)-10x+2;
б) y:= 5*sqrt(x)-10*x+2; г) y:= 5sqr(x)-10*x+2.
15. Какое значение примет переменная c в результате выполнения программы?
program pr1;
uses crt;
var a,b: byte;
begin
a:=1;
b:=a*a;
a:=a+1;
b:=a*a;
writeln(‘a=’,a,’ b=’,b);
end.
а) a=2, b=4; в) a=3, b=4;
б) а=6, b=2; г) a=4, b=2.
Вариант 2 Дата________
Контрольная работа в формате теста
по предмету Иформатика и ИКТ
учащегося(щейся) ____класса
МОУ «Амвросиевская школа №6» Амвросиевского района ДНР
____________________________________________________________________
Тема: «Алгоритмизация и программирование»
1. Запись алгоритма на языке конкретного исполнителя – это…
а) алгоритм; в) программа;
б) команда; г) исполнитель.
2. Отдельное указание исполнителю…
а) программа; в) команда;
б) алгоритм; г) приказ.
3. Исполнителем алгоритма может быть:
а) компьютер; в) человек;
б) дрессированное животное; г) все перечисленные выше варианты.
4. Алгоритмы, которые содержат команду повторения, называются..
а) линейными; в) циклическими;
б) разветвляющимися; г) вспомогательными.
5. Составная команда, в которой одни и те же действия (команды) повторяются несколько раз, называется…
а) командой присваивания; в) вспомогательной программой;
б) командой повторения; г) командой ветвления.
6. Графический способ описания алгоритма – это…
а) программа; в) алгоритм;
б) блок-схема; г) словесно-пошаговая запись.
7. Как записывается оператор присваивания на языке Pascal?
а) а = 1; в) а =: 1;
б) а := 1; г) а = ‘ 1’.
8. Подпрограмма, имеющая произвольное количество входных и выходных данных, называется:
а) процедурой; в) вспомогательным алгоритмом;
б) функцией; г) оператором
9. Алгоритм, целиком используемый в составе другого алгоритма, называется:
а) рекурсивным; в) основным;
б) вспомогательным; г) дополнительным.
10. Переменная характеризуется:
а) именем, типом, значением; в) значением, типом;
б) именем, значением; г) именем, типом.
11. Какая строка, из перечисленных ниже, описывает логическую переменную на языке Паскаль?
а) VAR X: INTEGER; в) VAR X: REAL;
б) VAR X: BOOLEAN; г) VAR X: CHAR.
12. Цикл while do это – …
а) цикл со счетчиком; в) цикл с предусловием;
б) цикл с постусловием; г) цикл с параметром.
13. Какие из перечисленных операторов являются операторами ввода данных?
а) and, or; в) if, then, else;
б) read, readln; г) write, writeln.
14. Укажите, правильную запись следующего математического выражения: L = (x2 +y2) ≤ R2
а) L:= (sqr(x) + sqr(y) ≤ R2; в) L:= (sqr(x) + sqr(y)) <= sqr (R);
б) L:= (sqr(x) + sqr(y) <= R2; г) L:= (sqr(x) + sqr(y) <= R*R;
15. Какие значения примут переменные С и D в результате выполнения программы?
Program V1;
Var a, b, c, d: integer;
begin
a:=6;
b:=2*a+8;
if b>a then c:= b-a else d:=a-b;
writeln (‘c=’, c);
writeln (‘d=’, d);
end.
а) c=14, d=0; в) d=14, d= -14;
б) c=38, d=14; г) d= -3, d=3.
Ответы на тесты
Вариант 1 |
Вариант 2 |
||
№ вопроса |
ответы |
№ вопроса |
ответы |
1 |
б |
1 |
в |
2 |
г |
2 |
в |
3 |
б |
3 |
г |
4 |
а |
4 |
в |
5 |
б |
5 |
б |
6 |
в |
6 |
б |
7 |
г |
7 |
в |
8 |
в |
8 |
А |
9 |
г |
9 |
б |
10 |
б |
10 |
а |
11 |
в |
11 |
б |
12 |
г |
12 |
в |
13 |
б |
13 |
б |
14 |
а |
14 |
в |
15 |
а |
15 |
а |
Добавил:
Upload
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:
Тесты по информатике Литвинова Е.В..doc
Скачиваний:
17
Добавлен:
14.11.2019
Размер:
111.62 Кб
Скачать
а) отладкой
задачи;
б) отладкой
исполнителя;
в) отладкой
алгоритма;
г) отладкой
программы.
27) Программы, в которых команды выполняются последовательно друг за другом, называются …
а) линейным;
б) разветвляющимися;
в) циклическими;
г) вспомогательными.
25) При заданных
исходных данных ( а=5, b=4)
определите результат выполнения
алгоритма, изображенного в виде
блок-схемы:
а) х=20;
б
)
х=9;
в) х=5;
г
)
х=4.
Х:=а*b
Х:=а+b
Гіпермаркет Знань>>Інформатика>>Інформатика 8 клас>> Інформатика: Алгоритми й основні алгоритмічні структури (повторення).
Практична робота до предмету Інформатика 8 клас.
а) программа; в) команда;
б) алгоритм; г) система команд?
Правильный ответ – б).
2. Запись алгоритма на языке конкретного исполнителя – это …
а) алгоритм; в) программа;
б) команда; г) исполнитель?
Правильный ответ – в).
3. Выявление ошибок и их устранение называется …
а) отладкой задачи; в) отладкой алгоритма;
б) отладкой исполнителя; г) отладкой программы?
Правильный ответ – г).
4. Отдельное указание исполнителю – это …
а) программа; б) алгоритм;
в) команда; г) приказ?
Правильный ответ – в).
5. Человек, робот, автомат, устройство, компьютер, который выполняет чьи-то команды, – это …
а) помощник; в) программа;
б) исполнитель; г) раб?
Правильный ответ – б).
6. Программы, которые содержат команду повторения, называются …
а) линейными; в) циклическими;
б) разветвляющимися; г) вспомогательными?
Правильный ответ – в).
7. Программы, в которых команды выполняются последовательно друг за другом, называются …
а) линейными; в) циклическими;
б) разветвляющимися; г) вспомогательными?
Правильный ответ – а).
8. Форма организации действий, при которой один и тот же блок выполняется несколько раз, называется …
а) следованием; в) ветвлением;
б) циклом; г) алгоритмом?
Правильный ответ – б).
9. Повторяющийся блок действий (команд) называется …
а) повтором; в) телом цикла;
б) циклом; г) командой повторения?
Правильный ответ – в).
10. Составная команда, в которой одни и те же действия (команды) повторяются несколько раз, называется …
а) командой присваивания;
б) командой повторения;
в) вспомогательной программой;
г) командой ветвления?
Правильный ответ – б).
11. Совокупность всех команд, которые может выполнить конкретный исполнитель, – это…
а) система программ; в) система команд;
б) система алгоритмов; г) система задач?
Правильный ответ – в).
12. Вспомогательная команда – это …
а) цикл; в) процедура;
б) ветвление; г) следование?
Правильный ответ – в).
13. Команда, у которой действия выполняются после проверки условия, называется …
а) командой цикла;
б) командой ветвления;
в) простой командой;
г) процедурой?
Правильный ответ – б).
14. Графический способ описания алгоритма – это …
а) программа; в) алгоритм;
б) блок-схема; г) словесно-пошаговая запись?
Правильный ответ – б).
15. Сложные условия – это такие условия, которые содержат …
а) логическую связку И;
б) логическую связку ИЛИ;
в) логическую связку НЕ;
г) логические связки И, ИЛИ, НЕ?
Надіслала вчитель математики та інформатики Філончук Олена Миколаївна, гімназія № 117 м. Києва Печерського району.
Предмети > Інформатика > Інформатика 8 клас > Алгоритми й основні алгоритмічні структури > Алгоритми й основні алгоритмічні структури. Практикуми, лабораторні, кейси
Авторські права | Privacy Policy |FAQ | Партнери | Контакти | Кейс-уроки
© Автор системы образования 7W и Гипермаркета Знаний — Владимир Спиваковский
При использовании материалов ресурса
ссылка на edufuture.biz обязательна (для интернет ресурсов —
гиперссылка).
edufuture.biz 2008-© Все права защищены.
Сайт edufuture.biz является порталом, в котором не предусмотрены темы политики, наркомании, алкоголизма, курения и других «взрослых» тем.
Разработка — Гипермаркет знаний 2008-
Ждем Ваши замечания и предложения на email:
По вопросам рекламы и спонсорства пишите на email:
Отладка, или debugging, — это поиск (локализация), анализ и устранение ошибок в программном обеспечении, которые были найдены во время тестирования.
Виды ошибок
Ошибки компиляции
Это простые ошибки, которые в компилируемых языках программирования выявляет компилятор (программа, которая преобразует текст на языке программирования в набор машинных кодов). Если компилятор показывает несколько ошибок, отладку кода начинают с исправления самой первой, так как она может быть причиной других.
В интерпретируемых языках (например Python) текст программы команда за командой переводится в машинный код и сразу исполняется. К моменту обнаружения ошибки часть программы уже может исполниться.
Ошибки компоновки
Ошибки связаны с разрешением внешних ссылок. Выявляет компоновщик (редактор связей) при объединении модулей программы. Простой пример — ситуация, когда требуется обращение к подпрограмме другого модуля, но при компоновке она не найдена. Ошибки также просто найти и устранить.
Ошибки выполнения (RUNTIME Error)
Ошибки, которые обнаруживают операционная система, аппаратные средства или пользователи при выполнении программы. Они считаются непредсказуемыми и проявляются после успешной компиляции и компоновки. Можно выделить четыре вида проявления таких ошибок:
- сообщение об ошибке, которую зафиксировали схемы контроля машинных команд. Это может быть переполнение разрядной сетки (когда старшие разряды результата операции не помещаются в выделенной области памяти), «деление на ноль», нарушение адресации и другие;
- сообщение об ошибке, которую зафиксировала операционная система. Она же, как правило, и документирует ошибку. Это нарушение защиты памяти, отсутствие файла с заданным именем, попытка записи на устройство, защищенное от записи;
- прекращение работы компьютера или зависание. Это и простые ошибки, которые не требуют перезагрузки компьютера, и более сложные, когда нужно выключать ПК;
- получение результатов, которые отличаются от ожидаемых. Программа работает стабильно, но выдает некорректный результат, который пользователь воспринимает за истину.
Ошибки выполнения можно разделить на три большие группы.
Ошибки определения данных или неверное определение исходных данных. Они могут появиться во время выполнения операций ввода-вывода.
К ним относятся:
- ошибки преобразования;
- ошибки данных;
- ошибки перезаписи.
Как правило, использование специальных технических средств для отладки (API-логгеров, логов операционной системы, профилировщиков и пр.) и программирование с защитой от ошибок помогает обнаружить и решить лишь часть из них.
Логические ошибки. Они могут возникать из ошибок, которые были допущены при выборе методов, разработке алгоритмов, определении структуры данных, кодировании модуля.
В эту группу входят:
- ошибки некорректного использования переменных. Сюда относятся неправильный выбор типов данных, использование индексов, выходящих за пределы определения массивов, использование переменных до присвоения переменной начального значения, нарушения соответствия типов данных;
- ошибки вычислений. Это некорректная работа с переменными, неправильное преобразование типов данных в процессе вычислений;
- ошибки взаимодействия модулей или межмодульного интерфейса. Это нарушение типов и последовательности при передаче параметров, области действия локальных и глобальных переменных, несоблюдение единства единиц измерения формальных и фактических параметров;
- неправильная реализация логики при программировании.
Ошибки накопления погрешностей. Могут возникать при неправильном округлении, игнорировании ограничений разрядной сетки, использовании приближенных методов вычислений и т.д.
Методы отладки программного обеспечения
Метод ручного тестирования
Отладка программы заключается в тестировании вручную с помощью тестового набора, при работе с которым была допущена ошибка. Несмотря на эффективность, метод не получится использовать для больших программ или программ со сложными вычислениями. Ручное тестирование применяется как составная часть других методов отладки.
Метод индукции
В основе отладки системы — тщательный анализ проявлений ошибки. Это могут быть сообщения об ошибке или неверные результаты вычислений. Например, если во время выполнения программы завис компьютер, то, чтобы найти фрагмент проявления ошибки, нужно проанализировать последние действия пользователя. На этапе отладки программы строятся гипотезы, каждая из них проверяется. Если гипотеза подтвердилась, информация об ошибке детализируется, если нет — выдвигаются новые.
Вот как выглядит процесс:
Важно, чтобы выдвинутая гипотеза объясняла все проявления ошибки. Если объясняется только их часть, то либо гипотеза неверна, либо ошибок несколько.
Метод дедукции
Сначала специалисты предлагают множество причин, по которым могла возникнуть ошибка. Затем анализируют их, исключают противоречащие имеющимся данным. Если все причины были исключены, проводят дополнительное тестирование. В обратном случае наиболее вероятную причину пытаются доказать.
Метод обратного прослеживания
Эффективен для небольших программ. Начинается с точки вывода неправильного результата. Для точки выдвигается гипотеза о значениях основных переменных, которые могли привести к ошибке. Далее на основании этой гипотезы строятся предположения о значениях переменных в предыдущей точке. Процесс продолжается до момента, пока не найдут ошибку.
Как выполняется отладка в современных IDE
Ранние отладчики, например gdb, представляли собой отдельные программы с интерфейсами командной строки. Более поздние, например первые версии Turbo Debugger, были автономными, но имели собственный графический интерфейс для облегчения работы. Сейчас большинство IDE имеют встроенный отладчик. Он использует такой же интерфейс, как и редактор кода, поэтому можно выполнять отладку в той же среде, которая используется для написания кода.
Отладчик позволяет разработчику контролировать выполнение и проверять (или изменять) состояние программ. Например, можно использовать отладчик для построчного выполнения программы, проверяя по ходу значения переменных. Сравнение фактических и ожидаемых значений переменных или наблюдение за ходом выполнения кода может помочь в отслеживании логических (семантических) ошибок.
Пошаговое выполнение — это набор связанных функций отладчика, позволяющих поэтапно выполнять код.
Шаг с заходом (step into)
Команда выполняет очередную инструкцию, а потом приостанавливает процесс, чтобы с помощью отладчика было можно проверить состояние программы. Если в выполняемом операторе есть вызов функции, step into заставляет программу переходить в начало вызываемой функции, где она приостанавливается.
Шаг с обходом (step over)
Команда также выполняет очередную инструкцию. Однако когда step into будет входить в вызовы функций и выполнять их строка за строкой, step over выполнит всю функцию, не останавливаясь, и вернет управление после ее выполнения. Команда step over позволяет пропустить функции, если разработчик уверен, что они уже исправлены, или не заинтересован в их отладке в данный момент.
Шаг с выходом (step out)
В отличие от step into и step over, step out выполняет не следующую строку кода, а весь оставшийся код функции, исполняемой в настоящее время. После возврата из функции он возвращает управление разработчику. Эта команда полезна, когда специалист случайно вошел в функцию, которую не нужно отлаживать.
Как правило, при пошаговом выполнении можно идти только вперед. Поэтому легко перешагнуть место, которое нужно проверить. Если это произошло, необходимо перезапустить отладку.
У некоторых отладчиков (таких как GDB 7.0, Visual Studio Enterprise Edition 15.5 и более поздних версий) есть возможность вернуться на шаг назад. Это полезно, если пропущена цель либо нужно повторно проверить выполненную инструкцию.