C 858993460 что это означает

от admin

Русские Блоги

На языке C мы определяем переменную int i, а не инициализированная, а затем вывод. Что это будет?

В приведенном выше экземпляре кода мы видим, что C -компиляторы определяют переменные Стоковое пространство Значение наполнения по умолчанию CC ,потому что i Это тип Int, тогда это четыре байта. Следовательно, количество байтов, которые не инициализируются, — это количество заполненных байтов 0xCCCCCCCC Затем вывод

-858993460 Какой призрак? На самом деле, мы могли бы также взять 0xCCCCCCCC Преобразовать в бинарный.

Студенты, которые узнали о негативных числах на компьютере, знают, что двоичный сначала — 1, а затем это означает, что это отрицательное число, поэтому мы можем пожелать найти контркод: (Символ неизменен, другая позиция занимает назад)

Ищу его для составления кода: (на основе обратного кода +1)

Тогда это число, двоичное значение памяти компьютера — верхний код выше, мы можем преобразовать его в десятичное значение, ответ -858993460

Существует также объяснение, почему наши начинающие игроки при написании программы не очень хорошо написаны, встретятся с большим количеством жировщиков, думая, что она искажена? На самом деле, это не так, это не имеет ничего общего с искаженным кодом. Искаженный код отличается, и кодирование будет искажено, потому что шестнадцатеричный китайский горячий китайский 0xCCCC Вы можете проверить, где высота или строка программы заканчивается «\ 0».

Кроме того, следует объяснить, что компилятор использует пространство кучи, а заполнение по умолчанию CD 。

Мы видим, что я подал заявку на 10 с ворскую память, и адрес памяти был заполнен 10 CD 。

Почему чтение char 'g' в int дает число -858993460 в этом коде?

Я выполнял упражнение для класса, и я решил посмотреть, что произойдет, если я наберу char когда код ожидает int . Я -858993460 букву ‘g’ чтобы посмотреть, что произойдет. это вывести -858993460 и я понятия не имею, почему.

Итак, откуда -858993460 этот -858993460 ?

2 ответа

Если извлечение завершится неудачей (например, если введена буква, в которой ожидается цифра), значение остается неизмененным и устанавливается битбит.

Кажется, это так. test не инициализирован; то вы получите распечатку случайного значения. Обратите внимание, что на самом деле это неопределенное поведение.

А поскольку С++ 11,

Если извлечение завершается неудачно, нуль записывается в значение и устанавливается битбита.

Это означает, что после С++ 11 вы получите значение 0 .

Если вы проверите результат чтения, вы увидите, что ничего не было прочитано.

Значение, которое вы печатаете, является неинициализированным значением test . Он может меняться от запуска до запуска. Технически, печать — это неопределенное поведение, поэтому ваша программа может даже сбой, хотя это вряд ли произойдет на практике.

printf displays "-858993460" or "╠╠╠╠╠╠╠╠"; what are these?

I am trying to build a program that encrypts a password and then does the reverse process (tells a correct password from an encrypted one).

For that, I have:

a password ( char[] type);

an encryption key (vector — int[] type) that has the same length as the char of the password;

two steps (placed also in a vector of type int step[2] ).

The requirement is that the encryption process has to be built using these two steps:

  • the first one (the value in step[0] ) is used to add the value (ASCII) starting from the first position of the password char to the first position of the encryption key vector for a number of steps equal to the first step step[0] ;

for example, adds char password[0] to int key[0] , then adds char password[1] to int key[1] and so on for a number of steps equal to the value placed in step[0] .

  • the second one ( step[1] ) subtracts from the corresponding position of the ASCII value of the password char , the value of the encryption key for a number of steps equal to the second step ( step[1] ).

for example, subtracts char password[5] from int key[5] , then subtracts char password[6] from int key[6] and so on for a number of steps equal to the value placed in step[1] .

And then, the process repeats until the end of the length of the password char.

I built a function as below that should do this (addition for a number of steps, then subtraction for a number of other steps, and repetition of the process until the end of the password char — the encryption key vector has the same length as the password char).

The result is placed in a new vector (for encryption) or in a new char (for the reverse process of finding the password).

Then if I try to printf the vector (for encryption process) in order to show the content of the vector, a message similar to this one appears:

Читать:
Как вставить лист из одного документа word в другой

why does it show «-858993460»?

Also, if a try to printf the char for showing the password in the reverse process (form an encrypted password to a readable one) using the following code,

then this message appears:

what is «╠»?

this «╠╠╠╠╠╠╠╠» is an incorrect display (the rest «côő

ypaXOF» is correct).

Also. I tried to add and subtract manually form [0] to the end of the string/vector and if I do that, no error message of type -858993460 or of type ╠╠╠╠╠╠╠╠ appears. It works fine and that tells me that the values in the char (password) or int (key) are correct.

If it is of importance, I work on Windows 64bit, but I use Visual Studio. Also, I have a Mac. There I have the same problem, but instead of -858993460 or ╠╠╠╠╠╠╠╠ I get other messages (for instance 0 instead of -858993460 ).

claudiu dragusin's user avatar

3 Answers 3

In the first function, you iterate i from 0 to n one step at a time. However, not all paths through the loop body assign anything to encryptedPass[i] — this is the case for both the last else if and when none of the if conditions matches. Likewise for the second function, but for Password1[i] .

At the end of each of these functions you do, however, unconditionally print all values from these arrays, which means they are uninitialized values. (And you iterate up to unknown values b6 and b7 , whereas you probably should iterate up to the same n that you use in the first loop.)

To fix, either ensure that each iteration writes something to the index, or have a separate write position index or pointer and only advance it when you write something.

Arkku's user avatar

There were a lot of changes I made to your code. Here is the list:

  • Added more #include tags for standard libraries (I’m guessing you already had some and didn’t post them)
  • Changed function arguments to be char* instead of char[] , it is not conventional to use char arrays in function arguments and I’m not even sure how they work in your code.
  • Got rid of uneccessary/extra variables: ap , bp and some others. Since C is pass-by-value, you don’t need temporary variables for the steps variables.
  • Fixed variable naming. A lot of your variable names were unintuitive/weird and I felt I had to change the names to something more accurate.
  • Used malloc (dynamic memory allocation) instead of placing char arrays on the stack. This is more flexible and reduces the chances of those gotchas, but does open up more possibility for segfaults.
  • Fixed your encryption/decryption algorithm since it would leave the char the same if it had just finished going through both steps ( ap == 0 && bp == 0 ).
  • Fixed some syntax errors.
  • Added some debugging fprintf statements, so you can see what’s going on.

As for your weird ╠ character, I can’t see why your code would print that other than maybe you have some memory error or your environment is switching between Unicode and ASCII or something. Frankly, I don’t want to figure it out because your code is kind of a mess and I don’t think you posted all of it because it had compilation errors when I first ran it.

I also added some null terminating characters ( ‘\0’ ) to the ends of the malloc ‘d strings that will be handy for properly printing the strings when debugging. Anyway, enough of that. Here’s the code:

NOTE: There is no error handling in this code, so if the user inputs are invalid in pretty much any way, the code will break and could lead to segfaults, infinite loops, etc. You should add error handling to every char* manipulation and array iteration before you use this in a properly-made application. And some sample output:

Получение -858993460 в результате переполнения стека

Программа отправляет мне значение -858993460 на a [ch] и b [nech] почему ?? я не могу понять это … если я использую cout<<m[i] на месте cout<<a[ch]<<endl; это работает нормально … показывает мне четные и шансы, но когда я пытаюсь отправить их в другой массив, значение идет не так (мне нужны эти еще два массива a [ch] и b [nech])

Решение

Вам нужно инициализировать ваши массивы

Без инициализации массива значение является случайным значением из стека.

Другие решения

m[i]=a[ch] неопределенное поведение, потому что a это массив неинициализированных int s.

Вы никогда не читаете в a , Какое поведение вы ожидаете?

Вы не инициализируете элементы a а также b в любом месте, поэтому они имеют довольно случайное начальное значение (например, значение -858993460, которое вы получаете).

Похожие статьи