开发者

Why does this C++ char array seem to be able to hold more than its size?

#include <iostream>
using namespace std;

typedef struct
{
    char streetName[5];

} RECORD;

int main()
{
    RECORD r;
    cin >> r.streetName;
    cout << r.streetName << endl;

}

When I run this program, if I enter in more than 5 characters, the output will show the whole string I entered. It does not truncate at 5 charac开发者_开发百科ters. Why is that?

How can I get this to work correctly?


You are overflowing the buffer. Put another char array after streetName and you will likely find that it gets the rest of the characters. Right now you are just corrupting some memory on your stack.


In order to limit the input to the size of the receiving array you need to use the length-limiting facilities provided by your input method. In your case you are using cin, which means that you can specify the limit by using its width method

cin.width(5);    
cin >> r.streetName;


Because cin sees streetName as a char * and writes to memory and there is nothing to stop writing to *(streetName + 6) and further. This is a form of buffer overrun

The best code in this case is define streetName as a std::string

i.e.

typedef struct
{
        std::string streetName;
} RECORD;


Because you're overruning the end of your buffer and in this particular case you're getting away with it. C and C++ make it very easy to "shoot yourself in the foot", but that doesn't mean that you should.


It's a buffer overrun.


C++ does not perform bounds checking on array accesses, and memory does not simply stop at the end of the array. You are writing data to memory that is not part of the array, the consequences of which are non-deterministic, and may sometimes even appear to work.

It is quite likely that if you placed that code into a function, the program would crash when you tried to return from the function, because one likely possibility is that you will have dumped on the function return address on the stack. You may also have corrupted data belonging to the calling function.


The way to do this correctly in c++ is to use a std::string.

#include<iostream>
#include<string>

....
std::string r;
getline(cin, r);
std::cout << r <<std::endl;

For truncated input(with suitably defined and inited values).

while(cin.peek() != EOF && i < len)
{
  cin >> arr[i];
  ++i;
}

You will want to do something after this to flush the buffer and not leave the rest of the line sitting on the input stream if you plan on doing other things with it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜