Pointers on C——6 Pointers.5

来源:互联网 发布:剑侠情缘手游数据互通 编辑:程序博客网 时间:2024/06/14 03:09

​6.5 Uninitialized and Illegal Pointer

The code fragment below illustrates a very common error:

下面这个代码段说明了一个极为常见的错误:


int *a;

...

*a = 12;


The declaration creates a pointer variable called a, and the assignment stores a 12 in the location to which a points.

这个声明创建了一个名叫a 的指针变量,后面那条赋值语句把12 存储在a 所指向的内存位置。


But where does a point? We declared the variable but never initialized it, so there is no way to predict where the value 12 is being stored. A pointer variable is no different from any other variable in this respect. If the variable is static, it is initialized to zero; but if the variable is automatic, it is not initialized at all. In neither case does declaring a pointer to an integer ʺcreateʺ any memory for the storage of an integer.

但是究竟a 指向哪里呢?我们声明了这个变量,但从未对它进行初始化,所以我们没有办法预测12 这个值将存储于什么地方。从这一点看,指针变量和其他变量并无区别。如采变量是静态的,它会被初始化为0; 但如果变量是自动的,它根本不会被初始化。无论是哪种情况,声明一个指向整型的指针都不会"创建"用于存储整型值的内存空间。


So what happens when this assignment is performed? If youʹre lucky, the initial value of a will be an illegal address, and the assignment will cause a fault that terminates the program. On UNIX systems, this error is called a ʺsegmentation violationʺ or a ʺmemory fault.ʺ It indicates that you have tried to access a location that is outside of the memory allocated to your program. On a PC running Windows, indirection on an unitialized or illegal pointer is one of the causes of General Protection Exceptions.

所以,如果程序执行这个赋值操作,会发生什么情况呢?如果你运气好, a 的初始值会是个非法地址,这样赋值语句将会出错,从而终止程序。在UNIX 系统上,这个错误被称为"段违例(segmentation violation) "或"内存错误 (memory fault)它提示程序试图访问一个并未分配给程序的内存位直。在一台运行Windows 的PC 上,对未初始化或非法指针进行问接的访问操作是一般保护性异常( General Protection Exception )的根源之一。


On machines that require integers to be at a particular boundary, accessing an address that is on the wrong boundary for its type also causes a fault. This error is reported on UNIX systems as a ʺbus error.ʺ

对于那些要求整数必须存储于特定边界的机器而言,如果这种类型的数据在内存中的存储地址处在错误的边界上,那么对这个地址进行访问时将会产生一个错误。这种错误在UNIX 系统中被称为"总线错误( bus error) " 。


A much more serious problem is when the pointer accidentally contains a legal address. What happens then is simple: the value at that location is changed, even though you had not intended to change it. Errors like this one are very difficult to find,because the erroneous code may be completely unrelated to the code that is supposed to manipulate the value that changed. Be extremely careful that pointer variables are initialized before applying indirection to them!

一个更为严重的情况是:这个指针偶尔可能包含了一个合法的地址。接下来的事很简单:位于那个位直的值被修改,虽然你并无意去修改它。像这种类型的错误非常难以捕捉,因为引发错误的代码可能与原先用于操作那个值的代码完全不相干。所以,在你对指针进行间接访问之前,必须非常小心,确保它们已被初始化!


上一章 Pointers on C——6 Pointers.4

原创粉丝点击