Following the tutorial site arrive in the sequence of characters.
So did the following example:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
int main()
{
char nome[4];
std::cout << "Entre com seu nome: ";
std::cin >> nome;
std::cout << nome;
return 0;
}
I noticed that if I exceed the character limit stated before nothing happens and the computer shows everything I wrote.
1 2 3 4 5 6 7 8
//Input
"parallelepiped"
// the input text has more characters than the input that I discover
// output
"parallelepiped"
//shows everything without cutting the string why this happens?
#include <iostream>
int main()
{
char name[4];
std::cout << "Enter your name: ";
std::cin >> name;
for (int i = 0; i <= 3; i++)
{
if (i == 3)
{
std::cout << name;
break;
}
name[i] = name[i];
std::cout << "OK! " << i << "\n";
}
return 0;
}
If I you enter the following string "cplusplus" he should show only "cplu" plus it shows "cplu" another character in the end after the "u" like a heart that is.
And so was wondering if someone could explain to me about the character limit.
Okay, so name is just a pointer to a memory location. The length of 4 says allocate 4 sequential bytes (because char is 1 byte in length, and 1 * 4 == 4.) Now a string of characters is just an array. By storing that array at name, you overwrite N (the length of the string) sequential bytes of memory starting at "name" (whatever address that is.) However, because only 4 bytes have been allocated, a string that has more then 4 characters (N > 4, including the null character at the end) will write into unallocated memory (or memory being used for something else in your program.) So, as your program continues that memory can be overridden because it was really being used for something else. Then when you try and print the string, it keeps printing chars 'till it hits '\0' (or 0x00) or the end of allocated memory. Since you don't know when that is now, you may get many various ascii characters along the way, as those bytes were not meant to be interpreted as ascii characters...
(Someone may want to read though that and make sure I got all that right... :)
This is a very bad kind of undefined behavior: you're writing to a stack-allocated array without checking for its bounds. If a malicious user gets a chance to run your program, they can trick it into executing any user-supplied code, using your access rights. It is as bad a security hole as the use of gets(name) or scanf("%s", name) in C.
Always, *always* limit the size of the input when writing to an array: