内存分配未成功,却使用了它

内存分配未成功,却使用了它。 编程新手常犯这种错误,因为他们没有意识到内存分配会不成功。

常用解决办法是, 在使用内存之前检查指针是否为 NULL。

如果指针 p 是函数的参数,那么在函数的入口 处用 assert(p!=NULL)进行检查。

如果是用 malloc 或 new 来申请内存,应该用 if(p==NULL) 或 if(p!=NULL)进行防错处理。

 

 1 #include <iostream>
 2 #include <string.h>
 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 4 using namespace std;
 5 int main(int argc, char** argv) {
 6        //拷贝字符串常量到字符数组
 7     char string[80] = "Fill the string with something";
 8     cout<<"string:"<<string<<endl;
 9     cout<<"strcpy:"<<endl;
10     char *p=strcpy(string,"abc");
11     cout<<"p     :"<<p<<endl;
12     cout<<"string:"<<string<<endl;
13     char str[80];
14     cout<<"str:";
15     cin>>str;
16     p=strcpy(string,str);
17     cout<<"p     :"<<p<<endl;
18     cout<<"string:"<<string<<endl;
19 
20     //拷贝前5个字符到string中
21     cout<<"str:";
22     cin>>str;
23     cout<<"strncpy:"<<endl;
24     p=strncpy(string,str,strlen(str));
25     cout<<"p     :"<<p<<endl;
26     cout<<"string:"<<string<<endl; 
27     return 0;
28 }

 

转载于:https://www.cnblogs.com/borter/p/9413650.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值