A
A
Andrey Golubkov2015-09-25 20:59:56
C++ / C#
Andrey Golubkov, 2015-09-25 20:59:56

Error "Run-Time Check Failure #2 - Stack around the variable 'n' was corrupted." How to fix?

#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
using namespace std;

void crypt()
{
   char c=0,f=0,b=0;
   unsigned char n=0;
  unsigned int UnitStateWord; /* слово состояния */
                /* ввод составных частей */
  printf("Status code (0 - 31) >");
  scanf_s("%d",&c);
  printf("is eror (0 / 1) >");
  scanf_s("%d",&f);
  printf("is busy (0 / 1) >");
  scanf_s("%d",&b);
  printf("transmit byte count  (0 - 255) >");
  scanf_s("%d",&n);
  /* формировние упакованного кода */
  UnitStateWord = ((unsigned int)c & 0x1F) << 11;
  UnitStateWord |= ((unsigned int)f & 1) << 9;
  UnitStateWord |= ((unsigned int)b & 1) << 8;
  UnitStateWord |= n & 0xFF;
  /* вывод результата */
  printf("Status = %x",UnitStateWord);
}
void decrypt()
{
 char c; /* код состояния */
 char f; /* признак ошибки */
 char b; /* признак занятости */
 unsigned char n; /* количество байт */
 unsigned int UnitStateWord; /* слово состояния */
  /* ввод слова состояния устройства */
  printf("Write status messge \n");
  printf("0 to 0xFFFF) >");
  scanf("%x",&UnitStateWord);
  /* Выделение составных частей */
  c=(UnitStateWord>>11)&0x1F;
  f=(UnitStateWord>>9)&1;
  b=(UnitStateWord>>8)&1;
  n=UnitStateWord&0xFF;
  /* вывод результатов */
  putchar('\n');
  printf("Status code                  = %d\n",c);
  printf("is eror            = %d\n",f);
  printf("is busy         = %d\n",b);
  printf("count = %d\n",n);
}
int main() {
  int i;
  cout<<"Write crypt(1) or decrupt(2)"<<endl;	
  cin>>i;
  if (i==1)
  { crypt();}
  if (i==2)
  { decrypt();}



  return 0;
}

When executing the first procedure - after displaying the result, it gives the error Run-Time Check Failure #2 - Stack around the variable 'n' was corrupted.
Perhaps it occurs due to variable overflow, How to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Владимир Мартьянов, 2015-09-25
@vilgeforce

scanf_s("%d",&c); - я думаю оно ждет указатель на long, а не на char. Вот и повреждение памяти.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question