-1

i wrote this code but i don't understand why char [ ] allows me to store more than 10 characters if your size is still 10 ?. Is normally what function cin.get() enable this?

#include <iostream>
using namespace std;

int main(){
char name[10];

cout<<"enter name: ";

cin.get(name,30);

cout<<"char[]: "<<name<<endl;

cout<<"size: "<<sizeof name;

return 0;
}
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
odiz
  • 21
  • 3

2 Answers2

2

Simply put, because it is C++. The design of the language reflects the hardware of its early days, in which a few bytes of memory were precious (which is still quite useful in some specialized environments, such as embedded hardware). To give you maximum control over the memory management, you as the programmer have a lot to say about where and when memory gets allocated (and deallocated!), which means you also have to do some of the related bookkeeping by yourself.

In this case, if you reserve 10 characters of memory and then tell another function it can write 30 bytes instead, it will trust that the variable you pass in has been properly prepared. It does mean you are writing in memory that is not allocated to you which may (read: will, at the moment you least expect it) have nasty side effects such as subtly changing variable values or just plain crashing your program.

The reason functions like cin.get accept the buffer size, is that you need to tell them how much memory that can use -- and that should never be more than you allocated. If you want to avoid this, you can use classes like std::string which try to take this low-level stuff off your hands.

CompuChip
  • 9,143
  • 4
  • 24
  • 48
1

It's undefined behavior. The C++ standard doesn't define what happens if you do that.

From the C++14 standard draft N4296, §1.3.24:

Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment(with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).


You may go one level beneath the standard, i.e., the operating system, which, besides other stuff, takes care of memory management.
The buffer name is allocated on the stack, next to stack frames, automatic variables, and thread-local variables.
When calling cin.get(name, 30), data may be written over the array's boundaries, effectively overwriting the data I enumerated. It may even happen that the call attempts to write over stack boundaries, which would almost certainly be caught by the OS.

Community
  • 1
  • 1
cadaniluk
  • 15,027
  • 2
  • 39
  • 67