Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading