PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] Why in C does taking input using int format to a char change the value of another char variable?

 July 20, 2022     c, char, integer, scanf     No comments   

Issue

I took input in "%d" format into a character using scanf() because I didn't want more than 8 bits. But doing so changed the value of another char variable.

Code:

#include <stdio.h>
int main() {
        char a;
        char b;
        printf("Enter a: ");
        scanf("%c", &a);
        printf("a = %c\n", a);
        printf("Enter b: ");
        scanf("%d", &b);
        printf("\na = %d\n", a);
        printf("b = %d\n", b);
}

Output:

Enter a: c
a = c
Enter b: 56

a = 0
b = 56

Screenshot


Solution

scanf reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments.

scanf("%d", &b);

With %d you are storing an integer into the char variable that can not hold an integer. the Variable now grows into the other variable in stack above it.

if you compile with the flag "-fstack-protector-all" you should get the *** stack smashing detected *** error on execution.



Answered By - JBahn77
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing