C++ Primer 第四版 例题不严谨导致的错误

1.该例题出自于6.7节的While的循环的使用(P178页):

int arr1[5]={0,1,2,3,4};
int *source=arr1;
size_t sz = sizeof(arr1)/sizeof(*arry1);
int *dest=new int[sz](0);
while(source != arr1+sz)
{
        *dest++=*source++;
} 
delete []dest; 

注意,最后一句调用将会出现运行时错误,因为现在dest指针指向的是dest[5],即第6个不存在的元素,如果现在使用delete删除dest指向的数组的话,将会删除未知的内存位置,解决办法是使用一个临时变量来保存dest指针的初始位置。


int arr1[5]={0,1,2,3,4};
int *source=arr1;
size_t sz = sizeof(arr1)/sizeof(*arry1);
int *dest=new int[sz](0);
int *temp=dest;
while(source != arr1+sz)
{
        *dest++=*source++;
} 

delete []temp;
dest=null;  
2.这一个例题出现在8.2的P248页:

int val;
while(cin>>val,!cin.eof())
{
        if(cin.bad())
        {
                throw runtime_error("IO stream corruped!");
        }
        if(cin.fail())
        {
                cerr<<"bad data,try agin!";
                cin,clear(istream::failbit);
                cin.ignore(numeric_limits<streamsize>::max(),'\n');
                continue;
        }
} 

如果输入一个无效的整形数据流,将会造成无线循环,问题的根源是clear的解释,clear跟setstate的作用相似,这里是设置流的failbit标志位为1,则就是说该流出现了一个fail错误,而不是书上所说的清除failbit的状态位。


请参考http://www.cppreference.com/wiki/io/clear
 void stream::clear( iostate flags = ios::goodbit );The function clear() does two things: 
 
it clears all io_stream_state_flags associated with the current stream,
and sets the flags denoted by flags


int val;
while(cin>>val,!cin.eof())
{
        if(cin.bad())
        {
                throw runtime_error("IO stream corruped!");
        }
        if(cin.fail())
        {
                cerr<<"bad data,try agin!";
                cin,clear(istream::goodbit);
                cin.ignore(numeric_limits<streamsize>::max(),'\n');
                continue;
        }
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值