-
Notifications
You must be signed in to change notification settings - Fork 21
Basic c #17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Basic c #17
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -39,11 +39,24 @@ int main() | |
|
|
||
| printf("Integer is %d\n", a); //print integer value | ||
| printf("Char is %c\n\n", b); //print character value | ||
|
|
||
|
|
||
|
|
||
| /*Takes the value entered by the user and displays the output*/ | ||
| int i; | ||
| char h[20]; | ||
| printf("Enter your name: \n"); | ||
| scanf("%s",h); //Takes input from the user | ||
| printf("Your name is: %s\n",h); | ||
| printf("Enter a number: \n"); | ||
| scanf("%d",&i); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If the input number does not fit in an signed integer it will roll over, if it is not a number it will set i to 0. Some error handling for these cases are good practice, see https://wiki.sei.cmu.edu/confluence/display/c/INT05-C.+Do+not+use+input+functions+to+convert+character+data+if+they+cannot+handle+all+possible+inputs |
||
| printf("Entered number is %d\n",i); | ||
|
|
||
|
|
||
| /*Very Important!!! Characters are also integers, look at ASCII table*/ | ||
| /*Another thing is chars are defined by ' ' not " ", strings are defined as " "*/ | ||
|
|
||
| printf("Char is %c, integer " | ||
| printf("\nChar is %c, integer " | ||
| "value is %d\n\n", b, b); //print char and integer value | ||
|
|
||
| /*printf can print more variables read the documentation*/ | ||
|
|
@@ -98,4 +111,4 @@ int main() | |
|
|
||
| getch(); //Standard function from stdio, wait for | ||
| return 0; | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using scanf like this is undefined behavior and can cause segfault or open up for malicious exploits. This will write the input to the stack until a word separator is found in the input, even if the input is longer than the size of the "h" buffer.
Use:
scanf("%19s", h); // leave 1 byte for the null-terminator
the rest of the line/word will be left in stdin and will be read by the next scanf instead of the number, so consider emptying stdin, e.g.
if (strlen(h) == sizeof(h)-1) while (getchar() != '\n'); // Empty left overs of name