Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions Basic_C_Examples/basic.c
Original file line number Diff line number Diff line change
Expand Up @@ -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

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

printf("Your name is: %s\n",h);
printf("Enter a number: \n");
scanf("%d",&i);

Choose a reason for hiding this comment

The 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*/
Expand Down Expand Up @@ -98,4 +111,4 @@ int main()

getch(); //Standard function from stdio, wait for
return 0;
}
}