C語言中野指標
阿新 • • 發佈:2018-12-15
野指標
野指標通常是因為指標變數中儲存的值不是一個合法的記憶體地址而造成的 野指標不是NULL指標,是指向不可用記憶體的指標 NULL指標不容易用錯,因為if語句很好判斷一個指標是不是NULL (注意:C語言中沒有任何手段可以判斷一個指標是否為野指標!)
野指標的由來
區域性指標變數沒有被初始化
#include <stdio.h> #include <string.h> struct Student { char* name; int number; }; int main() { struct Student s; strcpy(s.name, "Delphi Tang"); // 這裡的s.name未初始化 s.number = 99; return 0; }
使用已經釋放過後的指標
#include <stdio.h> #include <malloc.h> #include <string.h> void func(char* p) { printf("%s\n", p); free(p); } int main() { char* s = (char*)malloc(5); strcpy(s, "Delphi Tang"); func(s); printf("%s\n", s); // 在函式呼叫中指標已經釋放 return 0; }
指標所指向的變數在指標之前被銷燬
#include <stdio.h>
char* func()
{
char p[] = "Delphi Tang";
return p;
}
int main()
{
char* s = func();//func為呼叫函式,都是區域性變數,呼叫完成都銷燬
printf("%s\n", s); // 已經被銷燬
return 0;
}
我們在使用中一定要避免這些情況!