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

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

1
2
3
4
5
6
7
8
9
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指针的初始位置。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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页

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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;
        }
} 

如果输入一个无效的整形数据流,将会造成无限循环,问题的根源是在缓冲区并没有被完全清除。 请参考 http://www.cppreference.com/wiki/io/clear

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
/*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;
        }
} 
Licensed under CC BY-NC-SA 4.0
Built with Hugo
主题 StackJimmy 设计