野指針與避免



1.我們知道在程序中使用了一個野指針,會引起程序出錯,造成段錯誤。下面我舉一個例子指出野指針

  1. #include <stdio.h>  
  2.   
  3. int main()  
  4. {  
  5.     charchar *str;  
  6.   
  7.     printf("input a str\n");  
  8.     scanf(" %s", str);  
  9.   
  10.     printf("%s\n", str);  
  11.   
  12.     return 0;  
  13. }  
#include <stdio.h>

int main()
{
    char *str;

    printf("input a str\n");
    scanf(" %s", str);

    printf("%s\n", str);

    return 0;
}

下面我對*str進行賦值,會出現什麼後果呢?

  1. [root@localhost 0720]# ./a.out   
  2. input a str  
  3. hello  
  4. 段錯誤  
[root@localhost 0720]# ./a.out 
input a str
hello
段錯誤
我們看到運行結果出現了段錯誤!那是因爲str是野指針。

那什麼是野指針呢?野指針就是隨機指向一塊內存的指針。如果一個指針被定義成了野指針,那對這個指針的使用的危害是多麼的大,它可能改變程序中任何地方的值。

那到底是造成野指針的原因有哪些?

a.指針指向一塊已經釋放的內存。

b.指針指向一塊沒有訪問權限的內存。

下面我們來講講怎麼來避免野指針:

a.給指針賦值的時候,先檢查指針是否分配了合理的內存空間。

b.釋放內存的指針要給指針賦值爲NULL。(編碼規範)

比如:

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3.   
  4. int main()  
  5. {  
  6.     charchar *str;  
  7.   
  8.     str = (charchar *)malloc(sizeof(char) * 100);  
  9.     printf("input a str\n");  
  10.     scanf(" %s", str);  
  11.   
  12.     printf("%s\n", str);  
  13.   
  14.     return 0;  
  15. }  
  16. [root@localhost 0720]# ./a.out   
  17. input a str  
  18. hello  
  19. 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
在堆上分配了空間,就避免了野指針。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章