本博客文章合集html
指针是C语言一个很强大的功能。然而所谓成也萧何,败也萧何,用好了指针会使程序大放异彩,用错了指针轻者只是报个错,重者可能整个系统都崩溃了。本篇咱们来谈谈指针一种错误的使用方法”野指针“。
野指针通常是指定义时没有给初值的指针变量。来看如下程序:函数
#include <stdio.h> #include <string.h> int main() { char *source1 = "abc"; char *source2; printf("source2的值是:%u\n", source2); strcpy(source2 , source1); printf("%s",source2); return 0; }
这段程序定义了一个指向字符的指针source2,可是没有给它一个初始值。下面的代码就是将字符串”abc“复制到source2中,编译的结果以下:
--------------------Configuration: Test - Win32 Debug--------------------
Compiling...
demo.c
D:\CCode\Test\demo.c(8) : warning C4700: local variable 'source2' used without having been initialized
Linking...
Test.exe - 0 error(s), 1 warning(s)
编译给出一个告警,说source2没有初值就被使用了。你能够无视这个告警,而且运行程序,可是运行的结果多是灾难性的。
因为source2在定义时没有给初值,程序运行时系统会默认给source2一个值,咱们能够将程序中的
strcopy(source2 , source1);
printf("%s",source2);
这两行代码注释掉,而后运行程序,看看source2输出的值是多少。运行结果以下:
source2的值是:3435973836
Press any key to continue
可见source2被系统赋予一个值3435973836,而3435973836是一个内存的地址,至因而哪段内存地址,谁也不知道,多是操做系统自己所在的内存地址,也多是一个空的内存地址。若是是操做系统自己所在的内存地址,经过strcopy函数将”abc“复制给了这段内存地址,也就是修改了操做系统自己内存数据,你的计算机可能就崩掉了!因此指针在定义时必定要给一个初值,好比”NULL“。在本程序中,除了给source2赋初值外,还需使用malloc函数分配一块存储空间,使得source2指向这块存储空间。修改的程序以下:spa
#include <stdio.h> #include <string.h> #include<malloc.h> int main() { char *source1 = "abc"; char *source2 = NULL; printf("source2的初始值是:%u\n", source2); source2 = (char *)malloc(100); printf("source2的分配值是:%u\n", source2); strcpy(source2 , source1); printf("%s",source2); free(source2); source2 = NULL; return 0; }
在定义source2时赋初值NULL,在使用source2时分配一段内存空间,不用source2时释放内存空间,而且从新赋值NULL。操作系统