1.我們知道在程序中使用了一個野指針,會引起程序出錯,造成段錯誤。下面我舉一個例子指出野指針
- #include <stdio.h>
- int main()
- {
- charchar *str;
- printf("input a str\n");
- scanf(" %s", str);
- printf("%s\n", str);
- return 0;
- }
#include <stdio.h>
int main()
{
char *str;
printf("input a str\n");
scanf(" %s", str);
printf("%s\n", str);
return 0;
}
下面我對*str進行賦值,會出現什麼後果呢?
[root@localhost 0720]# ./a.out
input a str
hello
段錯誤
我們看到運行結果出現了段錯誤!那是因爲str是野指針。
那什麼是野指針呢?野指針就是隨機指向一塊內存的指針。如果一個指針被定義成了野指針,那對這個指針的使用的危害是多麼的大,它可能改變程序中任何地方的值。
那到底是造成野指針的原因有哪些?
a.指針指向一塊已經釋放的內存。
b.指針指向一塊沒有訪問權限的內存。
下面我們來講講怎麼來避免野指針:
a.給指針賦值的時候,先檢查指針是否分配了合理的內存空間。
b.釋放內存的指針要給指針賦值爲NULL。(編碼規範)
比如:
- #include <stdio.h>
- #include <stdlib.h>
- int main()
- {
- charchar *str;
- str = (charchar *)malloc(sizeof(char) * 100);
- printf("input a str\n");
- scanf(" %s", str);
- printf("%s\n", str);
- return 0;
- }
- [root@localhost 0720]# ./a.out
- input a str
- hello
- hello
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *str;
str = (char *)malloc(sizeof(char) * 100);
printf("input a str\n");
scanf(" %s", str);
printf("%s\n", str);
return 0;
}
[root@localhost 0720]# ./a.out
input a str
hello
hello
在堆上分配了空間,就避免了野指針。