Home > Enterprise >  Runtime check failure #2 when using char data type instead of int
Runtime check failure #2 when using char data type instead of int

Time:09-12

I've written a simple code in C that takes in an ASCII decimal value and returns the char value that corresponds to the inputted decimal. For example, 65 would print out 'A'.

int x;
printf("Enter an ASCII number: ");
scanf_s("%d", &x);
printf("Entered letter is: %c\n", x);

However if I change line 1 from int x to char x, the program will run into run-time check failure #2 stating stack around variable x was corrupted when I test the program with x = 65. I understand this usually happens if I am out of bounds of assigned memory, but 65 should still be within the memory limit of char. Why is this happening?

CodePudding user response:

By using scanf_s("%d", &x);, you tell c to scan for a decimal integer (%d) of type int, and store it in a char. Because an int is 4 bytes, and a char 1 byte, you are writing outside the char, corrupting the surrounding memory.

  •  Tags:  
  • c
  • Related