用 malloc 或 new 申請內存之后,應該立即檢查指針值是否為 NULL


用 malloc 或 new 申請內存之后,應該立即檢查指針值是否為 NULL。

防止使用指針值為 NULL 的內存。

 

 1 #include <iostream>
 2 #include <string.h>
 3 
 4 //main()函數
 5 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 6 using namespace std;
 7 int main(int argc, char** argv) {
 8         //聲明字符數組
 9     char ch,string[80],*p;
10     int n;
11 
12     //輸入字符串和要查找的字符
13     cout<<"Test strchr():"<<endl;
14     cout<<"string:";
15     cin>>string;
16     cout<<"ch    :";
17     cin>>ch;
18 
19     //在string中查找ch中的字符並顯示
20     p=strchr(string,ch);
21     cout<<"p    :"<<p<<endl;
22 
23     //輸入字符串和要查找的字符串並查找
24     char substr[80];
25     cout<<"Test strstr():"<<endl;
26     cout<<"substr:";
27     cin>>substr;
28 
29     //在string中查找substr中的字符串並顯示
30     p=strstr(string,substr);
31     cout<<"p    :"<<p<<endl;
32     return 0;
33 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM