指针强化

  • 指针是一种数据类型

指针变量

  • 指针是一种数据类型,占用内存空间,用来保存内存地址

空指针

  • 不允许向NULL和非法地址拷贝内存
  • 可以释放

野指针

  • 未初始化指针
  • malloc后也free了,但是指针没有置空
  • 指针操作超越变量作用域
  • 不可以释放,因为没有权限操作空间

代码示例:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//1、空指针 不允许向NULL和非法地址拷贝内存
void test01()
{
   
        //char *p = NULL;
        给p指向的内存区域拷贝
        //strcpy(p, "1111");//err
        //char*q = 0x1122;
        给q指向的内存区域拷贝内容
        //strcpy(q,"2222");//err
}
int *doWork()
{
   
        int a = 10;
        int *p = &a;
        return p;
}
//2、野指针
void test02()
{
   
        //int *p;//未初始化指针 会出错
        //printf("%d\n",*p);
        //2.malloc后也free了,但是指针没有置空
        //int *p = malloc(sizeof(int));
        //*p = 100;
        //free(p);//野指针
        //p = NULL;//将free后的指针要进行置空,防止野指针的出现
        //printf("%d\n", *p);
        //2、指针操作超越变量作用域
        int *p2 = doWork();
        printf("%d\n",*p2);
        printf("%d\n", *p2);
}
void test03()
{
   
        int *p = NULL;
        free(p);//空指针是可以释放的
        free(p);
        int *p2 = malloc(4);
        free(p2);
        free(p2);//野指针不可以释放的
}
int main()
{
   
        //test01();
        test02();
        system("pause");
        return EXIT_SUCCESS;
}