T
T
Type Programmer2018-08-15 23:33:38
C++ / C#
Type Programmer, 2018-08-15 23:33:38

C ++ when you enter one variable, does the second one change?

It was like this, I wrote myself what thread of the program from the flashlight, purely to write
Here is the code:

#include <iostream>
using namespace std;

int main()
{
//  Simple coder, cimple decoder
int krypt,i;
char word[5];
char data[4096];
char krypted[5001];
///////////////////////////////
cout << "Crypt number : ";
cin >> krypt;
cout << "Uncrypt word : ";
cin >> word;
cout << "Crypt data : ";
cin >> data;

cout << endl << endl  << "Crypt number : " << krypt << endl << "Uncrypt word : " << word << endl << "Start crypting? Y/N" << endl;

It seems to be nothing out of the ordinary, but the variable krypt, it is not clear why, from different inputs of other data, namely arrays.
cout << endl << endl  << "Crypt number : " << krypt << endl << "Uncrypt word : " << word << endl << "Start crypting? Y/N" << endl;

In this line, I see that the krypt variable has changed its value for some reason, I can't figure out why.
Here is a piece of the console.
Situation 1:
Crypt number : 54414
Uncrypt word : Hellow
Crypt data : 0989091


Crypt number : 119
Uncrypt word : Hellow
Start crypting? Y/N

Situation 2:
Crypt number : 54414
Uncrypt word : Hello
Crypt data : 0989091


Crypt number : 54272
Uncrypt word : Hello
Start crypting? Y/N

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2018-08-16
@MegaCraZy6

It seems that on this platform the stack grows downwards (in the direction of decreasing addresses), therefore, having entered
6 characters in word (word size is 5), the array went beyond the limits and the last 2 bytes (do not forget that strings in C also have an additional zero symbol at the end) are written to neighboring variables, i.e. corrupted the values ​​contained in them.
There was no failure, because all the variables are on the stack (and all the space on the stack is already allocated from the beginning and can be freely accessed). If word were a dynamic array, then most likely a seg fault would occur. In the debug version, it might not have happened.
C and C++ leave it up to the programmer to manage memory, so the compiler doesn't keep track of such things.
If you want to get rid of the error, use the string class or rewrite the code so that it would not be possible to overflow the array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question