【扩展知识4】
1. 野指针
2. %p的使用
( 1 )野指针
定义:野指针”不是NULL指针,是指向“垃圾”内存的指针。[重量级危险人物]
野指针的成因:
1. 指针变量定义时没有初始化。
2. 指针变量free后没有置于NULL。
3. 指针的使用超出范围
程序举例:
[ 程序1 ]
//指针变量没有初始化
#include<stdio.h>
int main( void)
{
char *cp; //定义char型指针,但是没有初始化。
int *ip; //定义int型指针,也没有初始化
float score; //float型变量
float *fp= &score; //定义float指针变量 ,并指向score。
int num= 10;
int *ptr1; //定义int型变量,这里没初始化
ptr1= # //让ptr指向变量num的地址.&是取地址符。
char *pt= NULL; //一开始就初始化为NULL。
//以上除了cp、ip是野指针的话,其余的都不是。
return 0;
}
[程序 2 ]
//指针变量free后没有置于NULL
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int n= 100;
char *ptr;
ptr= ( char * )malloc( n* sizeof( char ) ); //分配100字节的空间
if( ptr== NULL )
{
printf( "内存分配失败!\n");
exit( 1 );
}
//其他操作省略
//free释放内存
free( ptr ); //注意malloc等分配内存函数,必须与free配套使用
ptr= NULL; //使ptr不是野指针。
return 0;
}
说明:
Free释放指针后,要把指针赋值为NULL。如果不赋值为NULL(会指向乱码),我们就无法使用if语句判断指针是否为NULL了。
[程序 3 ]
#include <stdio.h>
#include <stdlib.h> //for malloc,free,exit
#define N 100
//print函数的声明
void print( void );
int main( void )
{
char*str= NULL;
str=( char * )malloc( N* sizeof( char ) );
if(str== NULL )
{
printf("内存分配失败!\n" );
exit(1 );
}
print();
free(str );
str=NULL;
return0;
}
void print( void )
{
//str越界使用!!!
strcpy(str, "hello" );
return;
}
说明:
程序中虽然定义str并为其分配内存,但其作用仅在main中。函数print函数中的str虽然同名,但与main的str却不相同。所以,编译时就报错,print中的str没有定义。
( 2 )%p是什么?
我们可能对常用的%d,%f,%x等比较熟悉吧,对%p却很陌生。其实,%p就是以十六进制打印地址,相当于00%X打印地址。
格式控制符“%p”中的p是pointer(指针)的缩写。指针的值都是一个表示地址空间中某个存储器单元的整数。printf函数族中对于%p一般以十六进制整数方式输出指针的值,附加前缀00。
[程序]
//编译环境:VC++6.0
#include <stdio.h>
int main( void )
{
intnum;
printf("%p\n", &num );
printf( "00%X\n", &num );
return0;
}
运行结果:
0022FEBC
0022FEBC
【指尖的微笑】错误在所难免,希望得到大家的指正^-^
转载时保留原文的链接http://oursharingclub.joinbbs.net和http://blog.csdn.net/mirrorsbeyourself