#include <stdio.h> #include <stdlib.h> int main(void) { int *p1; int *p2; p2=p1=malloc(sizeof(int)); printf("Please input a number:\n"); scanf("%d", p1); free(p1); printf("%d\n", *p2); return 0; }
參見上例代碼,兩個指針p1、p2指向同一個由malloc分配的空間,free掉p1,引用p2時,出現瞭如下錯誤:
這是怎麼回事呢?
free對應着malloc,當你malloc一塊內存時,相當於機器將這塊內存借給你,你可以隨意使用這塊內存,其他程序就不會使用這塊內存。而一旦free後,相當於將這塊內存還給了機器,機器就可以將這塊內存借給其他程序了。p2還是指向了這塊內存,成爲了野指針,一旦對其進行操作,很可能會破壞其他使用這塊內存的程序的數據。
那麼如何規避這種風險呢?
可以先將要釋放的指針指向NULL,再free。即
#include <stdio.h> #include <stdlib.h> int main(void) { int *p1; int *p2; p2=p1=malloc(sizeof(int)); printf("Please input a number:\n"); scanf("%d", p1); //先將p1指向NULL再釋放 p1=NULL; free(p1); printf("%d\n", *p2); return 0; }