歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言指針越界訪問示例

C語言指針越界訪問示例

日期:2017/3/1 10:05:25   编辑:Linux編程

C語言對數組下標不做檢查,指針常常越界訪問;我們編程時要特別注意。

一、示范代碼

#include<iostream.h>
#include<memory.h>
int a[10];
int b[10];
void main()
{
memset(a,0,sizeof(int)*10);
memset(b,0,sizeof(int)*10);
a[10]=10;
cout<<b[0]<<endl;
}

在上例中,編譯鏈接通過,但程序運行結果 b[0]=10;

輸出a[10]和b[0]地址:

#include <iostream.h>
#include<memory.h>
int a[10];
int b[10];
void main()
{
cout<<hex<<(unsigned int)&a[10]<<endl;
cout<<hex<<(unsigned int)&b[0]<<endl;
}

結果:

a[10] 地址為 0x41454c

b[0]地址為 0x41454c

備注:上述程序在vc6.0下編譯,不同編譯系統地址值可能不同;但a[10]和b[0]地址值始終相同。

二、解釋

連續定義的全局變量在內存中是連續存放的,同時C對數組下標不做檢查;指針越界訪問內存,編譯器不會提示錯誤。利用越界的指針讀寫內存,輕則程序結果錯誤,重則直接導致程序崩潰。

Copyright © Linux教程網 All Rights Reserved