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 more than 5 characters, the entire input line will be displayed on the output. It is not cropped with 5 characters. Why is this?

How can I make this work correctly?

+4
source share
7 answers

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

+13
source

To limit the input to the size of the receiving array, you need to use the length constraints provided by your input method. In your case, you are using cin , which means you can specify a constraint using the width method

 cin.width(5); cin >> r.streetName; 
+6
source

Because you are overflowing the end of your buffer, and in this particular case you are dealing with this. C and C ++ make it easy to shoot yourself in the foot , but that doesn’t mean you should.

+5
source

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

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

i.e.

 typedef struct { std::string streetName; } RECORD; 
+5
source
+3
source

The way to do it right in C ++ is to use std :: string.

 #include<iostream> #include<string> .... std::string r; getline(cin, r); std::cout << r <<std::endl; 

For truncated input (with corresponding defined and entered values).

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

After that, you will want to do something to clear the buffer and not leave the rest of the line sitting on the input stream if you plan to do other things with it.

+3
source

C ++ does not check the bounds of access to the array, and memory does not just stop at the end of the array. You write data to memory that is not part of the array, the consequences of which are not deterministic and can sometimes even work.

It is very likely that if you put this code in a function, the program will crash when you try to return from this function, because one of the possible possibilities is that you will be reset to the return address of the function on the stack. You may also have corrupted data belonging to the calling function.

+3
source

Source: https://habr.com/ru/post/1310621/


All Articles