Skip to Content
C++程序设计:原理与实践(基础篇)(原书第2版)
book

C++程序设计:原理与实践(基础篇)(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
9h 36m
Chinese
Pearson
Content preview from C++程序设计:原理与实践(基础篇)(原书第2版)

12.4.3 指针范围

指针带来的主要问题是一个指针并不“知道”它指向多少个元素。考虑下面代码:

pd是否有第三个元素pd[2]?它是否有第五个元素pd[4]?如果查看pd的定义,我们发现答案分别是“是”和“否”。但是,编译器不知道这些;它并不跟踪指针的值。这段代码只是简单地访问内存,就像我们已经分配的足够的内存一样。它甚至会访问pd[-3],就像pd指向的地址往前三个double的位置也是我们分配的内存的一部分一样:

我们并不知道标记为pd[-3]和pd[4]的内存位置被用于什么。但是,即使我们知道也不意味着它们可以作为pd指向的包含三个double的数组的一部分。最有可能的情况是,它们是其他对象的一部分,而我们将它们弄得乱七八糟。这不是一个好主意。实际上,这是一个典型的灾难性的坏主意:“灾难性”表现在“我的程序神秘崩溃”或“我的程序得到错误的输出”。尝试着大声说出来;它听起来根本不好。我们要走很长一段路来避免这种错误。越界访问特别令人讨厌,因为程序中明显无关的部分会受到影响。一次越界的读取会给我们一个“随机”值,它可能依赖于某些完全无关的计算。一次越界的写入会将某些对象变成“不可能”的状态,或者简单地赋予它一个不期望的错误值。这种写入通常在发生后很长时间内都不会被注意到,因此很难被发现。更糟糕的是:你运行一个带有越界错误的程序两次,输入稍有不同就可能出现不同的结果。这种错误(“瞬时错误”)是最难发现的错误之一。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

C++语言导学(原书第2版)

C++语言导学(原书第2版)

本贾尼 斯特劳斯特鲁普
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano

Publisher Resources

ISBN: 9787111562252