Share to: share facebook share twitter share wa share telegram print page

边界检查

边界检查程序设计中是指在使用某变量前,检查该变量的值是否处在指定的范围之内。最常见的是数组的下标检查,防止下标超出数组范围,覆盖、運行其他堆疊位址数据。

若是變數超過範圍,而边界检查沒檢查到发,有可能是程序出现异常并终止运行,但也可能出现其他现象。

由于每次都进行边界检查非常耗时,而且有些代码确定不会出现越界问题,所以这个操作并不总是需要被执行。一些现代编译器中有称为选择性边界检查的技术,可以略去一些常见的不需要的边界检查,从而提高程序的性能。

各编程语言的应用情况

在目前常见的编程语言中,强制进行边界检查的有C#AdaHaskellJavaJavaScriptLispPHPPythonRubyVisual Basic。其中C#同时支持“unsafe块”(不安全代码块),即一段暂时关闭边界检查、启用指针以提高效率的代码块。这个功能常被用于加速一小段不可能出现越界问题的代码的执行速度,而不至于破坏整个程序的安全性。除了这些语言,D语言OCaml也支持自动边界检查,但是允许用户通过编译器的一个开关选项来选择是否启用该功能。

差一错误,又称“栅栏错误”:一个栅栏被一些柱子分割成10段,柱子的根数应该是11根,而不是10根。

然而,有一些编程语言(比如C语言)为了提高速度,从来都不会自动进行边界检查,这经常导致差一错误(见右图)和缓冲区溢出的发生。许多程序员认为这些语言为了速度所付出的代价太大了。在1980年图灵奖讲座上,東尼·霍爾讲述了他设计包含边界检查的ALGOL 60语言时的经历[1]

范围检查

范围检查经常被用于确保某个数字处在一个特定的范围之内。通常在访问数组的时候会进行该检查,因为当数组下标越界的时候,数据会被写入其它变量的空间,甚至会覆盖压栈的寄存器数值。这样一来,程序可能会崩溃,或者是导致一些安全漏洞的产生(见缓冲区溢出)。在Java中,Java虚拟机将在尝试访问数组中的元素的时候,自动的进行数组边界检查,并且在下标越界的时候引发异常[2]

范围检查的另一个常见用途是在两种数据类型相互转换的时候。在构建在.NET Framework上的语言中,超出范围的强制转换将引发InvalidCastException类型的异常。[3]

比如将一个32位有符号整数类型的变量强制转换到一个16位有符号整数类型的变量之前,会检查这个变量的值是否在-32768~+32767之间(16位有符号整数可以表示的整数范围),而不是诸如32768之类的无法表示的数字。

数组下标检查

数组下标检查是指在程序中,所有数组下标的表达式的结果在真正被用来访问某一个特定的元素之前,先把它的值和定义数组时给出的数组上界和下界进行比较。如果一个下标超出了预期的范围时,那么就引发一个错误来阻止进一步的访问。(例如:.NET Framework中的IndexOutOfRangeException[4]和ArgumentOutOfRangeException[5]类型异常

比如在访问一个下标范围是0~9的数组前检查下标是否也在0~9内,而不是如25之类的越过数组结尾的下标。

除了软件实现的下标检查之外,VAX架构的电脑拥有一条INDEX汇编指令,可以用来检查数组的下标是否越界,可以至多提供6个任意VAX编址的地址。B6500和一些相似的伯勒斯电脑则以硬件进行边界检查,无论是采用什么语言撰写的程序。[6]

数据验证

在数据集合数据质量范畴中,边界检查表示检查一个并不总是错误的数据。比如,一个成年人的身高应该处在0到3米之间、利用率应该在0到1之间等。

参见

参考

  1. ^ The Emperor’s Old Clothes”, The 1980 ACM Turing Award Lecture, CACM volume 24 number 2, February 1981, pp 75–83.
  2. ^ 存档副本. [2011-11-10]. (原始内容存档于2011-11-20). 
  3. ^ 存档副本. [2011-11-10]. (原始内容存档于2016-03-28). 
  4. ^ 存档副本. [2011-11-10]. (原始内容存档于2017-01-15). 
  5. ^ http://msdn.microsoft.com/library/zh-cn/system.collections.arraylist.item.aspx
  6. ^ Adar Nir, Grosman Rotem. VAX-11 Assembler and Simulator. Technion, Israel Institute of Technology.: p.42. [2011-11-10]. (原始内容 (pdf)存档于2020-02-22) (英语). A subscript range trap is an exception indicating that the last instruction was an INDEX instruction with the subscript operand is lower than the low operand orgreater than the high operand. 
Read more information:

2021 novel by Dave Eggers The Every Book cover of The EveryAuthorDave EggersCover artistEve Weinsheimer and Jessica HischeCountryUnited StatesLanguageEnglishGenreScience fictionPublisherVintagePublication dateOctober 5, 2021 (hardcover), November 16, 2021 (paperback)Media typePrint (hardcover & paperback), audiobook, e-bookPages608 pp. (first edition, paperback)ISBN978-0-593-31534-7 (first edition, paperback) The Every is a 2021 dystopian novel written by American author Dave Egger…

English magazine editor (1958–2007) This British surname is barrelled, being made up of multiple names. It should be written as Delves Broughton at birth. Isabella BlowBlow in 2005BornIsabella Delves Broughton(1958-11-19)19 November 1958London, EnglandDied7 May 2007(2007-05-07) (aged 48)Gloucester, Gloucestershire, EnglandResting placeGloucester CathedralYears active1993–2007Spouses Nicholas Taylor ​ ​(m. 1981; div. 1983)​ Detmar Blow…

Japanese manga series & television anime This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Battle B-Daman – news · newspapers · books · scholar · JSTOR (January 2014) (Learn how and when to remove this template message) This article may need to be rewritten to comply with Wikipedia's quality standards. You ca…

American video game developer Insomniac Games, Inc.Insomniac's logo since 2017FormerlyXtreme Software, Inc. (1994–1995)TypeSubsidiaryIndustryVideo gamesFoundedFebruary 28, 1994; 29 years ago (1994-02-28)FounderTed PriceHeadquartersBurbank, California, USNumber of locations2 studiosKey peopleTed Price (CEO)ProductsSpyro series (1998–2000)Ratchet & Clank series (2002–present)Resistance series (2006–2011)Sunset Overdrive (2014)Marvel's Spider-Man (2018–present)Number…

Campeonato MundialAtletismo 2019 Provas de pista 100 m masc fem 200 m masc fem 400 m masc fem 800 m masc fem 1500 m masc fem 5000 m masc fem 10000 m masc fem 100 m com barreiras fem 110 m com barreiras masc 400 m com barreiras masc fem 3000 mcom obstáculos masc fem Revezamento 4×100 m masc fem Revezamento 4×400 m masc fem mis Provas de estrada Maratona masc fem 20 km marcha atlética masc fem 50 km marcha atlética masc fem Provas de campo Salto em distância masc fem Salto triplo mas…

1945 film by Roy William Neill Pursuit to Algiers1946 US theatrical posterDirected byRoy William NeillScreenplay byLeonard LeeBased onCharactersby Sir Arthur Conan DoyleProduced byHoward BenedictStarringBasil RathboneNigel BruceCinematographyPaul IvanoEdited bySaul A. GoodkindMusic byEdgar FairchildDistributed byUniversal PicturesRelease date October 26, 1945 (1945-10-26) Running time65 minutesCountryUnited StatesLanguageEnglish Pursuit to Algiers (1945) is the twelfth entry in th…

1987 film by Élie Chouraqui Man on FireTheatrical release posterDirected byÉlie ChouraquiScreenplay byElie ChouraquiSergio DonatiFabrice ZiolkowskiBased onMan on Fireby A. J. QuinnellProduced byArnon MilchanStarring Scott Glenn Jade Malle Joe Pesci Brooke Adams Jonathan Pryce Danny Aiello Paul Shenar Narrated byScott GlennCinematographyGerry FisherEdited byNoëlle BoissonMusic byJohn ScottProductioncompanies7 Films CinémaCima ProduzioniFrance 3 CinémaSep FilmsDistributed byActeurs Auteurs As…

Indian filmOnenessOneness - First PosterDirected byPriyakanta LaishramProduced byRoushil SinglaPriyakanta LaishramStarringMaya ChoudhuryPriyakanta LaishramSuraj NgashepamSachinker SagolsemProductioncompanyPriyakanta ProductionsCountryIndiaLanguageMeitei language (officially called Manipuri language) Oneness is an upcoming 2023 Manipuri movie directed by Priyakanta Laishram. It is the first gay-themed movie of Manipur, Northeast India. It is the first mainstream Manipuri movie to deal with same-s…

School in Duxbury, Plymouth County, Massachusetts, United StatesDuxbury High SchoolFront of Duxbury High SchoolAddress71 Alden StreetDuxbury, Plymouth County, Massachusetts 02332United StatesCoordinates42°02′31″N 70°40′27″W / 42.041999832°N 70.67416397°W / 42.041999832; -70.67416397InformationSchool typePublic, PublicMottoSoar to New HeightsEstablished1866; 157 years ago (1866)School districtDuxbury Public SchoolsNCES District ID2504410Superi…

Leader of East Germany from 1949 to 1950 Wilhelm PieckPieck in 1952Chairman of the Socialist Unity PartyIn office22 April 1946 – 25 July 1950Serving with Otto GrotewohlDeputyWalter UlbrichtMax FechnerPreceded byPosition establishedSucceeded byWalter Ulbricht(as General Secretary)President of East GermanyIn office11 October 1949 – 7 September 1960Preceded byKarl Dönitz (as President of the Reich)Succeeded byWalter Ulbricht (as Chairman of the State Council) Parliame…

2006 action-adventure video game 2006 video gameBullyNTSC cover art for PlayStation 2Developer(s)Rockstar Vancouver[a]Publisher(s)Rockstar GamesProducer(s)Jeronimo BarreraSteve MartinDesigner(s)Mike SkupaSergei KuprejanovProgrammer(s)Mike SlettPeter GrantArtist(s)Steven OldsWriter(s)Dan HouserJacob KrarupComposer(s)Shawn LeeEngineRenderWareGamebryo[b]Platform(s)PlayStation 2WiiXbox 360WindowsAndroidiOSRelease 17 October 2006 PlayStation 2NA: 17 October 2006EU: 25 October 2006AU: …

Anton Grygoryevich RubinsteinSinh28 tháng 11 năm 1829 (lịch Nga cũ: 16 tháng 11Vikhvatinets, Podolsk, NgaMất20 tháng 11, 1894(1894-11-20) (64 tuổi)Peterhof, NgaQuốc tịch NgaSự nghiệp khoa họcNgànhNhà soạn nhạcNơi công tác Nhạc viện Sankt Petersburg Viện Pháp quốc Các nghiên cứu sinh nổi tiếng Pyotr Ilyich Tchaikovsky Josef Hofmann Herman Laroche Anton Grygoryevich Rubinstein (tiếng Nga: Антон Григорьевич Рубинште…

Norwegian goldsmith, artist, and designer Grete Prytz KittelsenBornAdelgunde Margrethe Prytz(1917-06-28)June 28, 1917Oslo, NorwayDiedSeptember 25, 2010(2010-09-25) (aged 93)Oslo, NorwayNationalityNorwegianAlma materIllinois Institute of TechnologyOslo National Academy of the ArtsSpouseArne Korsmo Grete Prytz Kittelsen (born Adelgunde Margrethe Prytz, June 28, 1917, Oslo, died September 25, 2010, Oslo), was a Norwegian goldsmith, enamel artist, and designer. She is one of the most well-…

Северо-Кавказский филиал ордена Трудового Красного знамени федерального государственного бюджетного образовательного учреждения высшего образования Московский технический университет связи и информатики(СКФ МТУСИ) Международное название North Caucasus Branch Moscow Technical University o…

Art curator This article is an orphan, as no other articles link to it. Please introduce links to this page from related articles; try the Find link tool for suggestions. (April 2023) Ajayya KumarBornCherpu, Thrissur, KeralaNationalityIndianEducationDoctorate in ManagementAlma materInstitute of Cost Accountants of India, Institute of Management Accountants USA, American Academy of Financial ManagementOccupation(s)Art curator, Author, COOAjayya Kumar is a COO, Author, Management Thinker &…

Species of mammal Yellow golden mole[1] Conservation status Least Concern (IUCN 3.1)[2] Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Chordata Class: Mammalia Order: Afrosoricida Family: Chrysochloridae Genus: Calcochloris Species: C. obtusirostris Binomial name Calcochloris obtusirostris(Peters, 1851) Yellow golden mole range Synonyms ''Calcochloris antedatesChrysotricha obtusirostrisHuetia obtusirostris'' The yellow golden mole (Calcochloris ob…

العلاقات البالاوية الليسوتوية بالاو ليسوتو   بالاو   ليسوتو تعديل مصدري - تعديل   العلاقات البالاوية الليسوتوية هي العلاقات الثنائية التي تجمع بين بالاو وليسوتو.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين: وجه المقارنة با…

Community settlement in central Israel Place in Central, IsraelKarmei Yosef כַּרְמֵי יוֹסֵף‎كرمي يوسفKarmei Yosef from Tel GezerEtymology: Yosef's VineyardsKarmei YosefCoordinates: 31°50′54″N 34°55′13″E / 31.84833°N 34.92028°E / 31.84833; 34.92028CountryIsraelDistrictCentralCouncilGezerFounded1984Founded byFormer residents of Ness Ziona and RehovotPopulation (2021)[1]1,757Websitewww.karmeyyosef.org Karmei Yosef (Hebrew:…

Space-filling tiling with cells of 6 faces A trivial example of a Corner-point grid with only two cells. In geometry, a corner-point grid is a tessellation of a Euclidean 3D volume, where the base cell has 6 faces (hexahedron). A set of straight lines defined by their end points define the pillars of the corner-point grid. The pillars have a lexicographical ordering that determines neighbouring pillars. On each pillar, a constant number of nodes (corner-points) is defined. A corner-point cell is…

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Oktober 2022. 'Julia Buccola Petta (1892 – March 17, 1921) adalah seorang ibu rumah tangga yang dikenal setelah kematiannya sebagai Pengantin Italia. Dia adalah putri Filomena Buccola dan istri Matthew Petta. Dia meninggal pada usia 29 pada tahun 1921 saat melahirkan…

Kembali kehalaman sebelumnya

Lokasi Pengunjung: 54.158.248.39