#include <stdio.h>
int num1;
int num2;
int res;
static int add(void) {
res = num1 + num2;
printf("\nAnswer: %u", res);
}
static int sub(void) {
res = num1 - num2;
printf("\nAnswer: %u", res);
}
static int mal(void) {
res = num1 * num2;
printf("\nAnswer: %u", res);
}
static int div(void) {
res = num1 / num2;
printf("\nAnswer: %u", res);
}
void do_operator() {
char op[1];
printf("Enter an operator (+, -, *, /):");
scanf("%s", &op);
if (*op == '+')
{
add();
}
else if (*op == '*')
{
mal();
}
else if (*op == '-')
{
sub();
}
else if (*op == '/')
{
div();
}
else
{
printf("\nNo valid input: %s", op);
}
}
int main() {
printf("\nEnter number-1:");
scanf("%u", &num1);
printf("\nEnter number-2:");
scanf("%u", &num2);
do_operator();
return 0;
}
Hey, I’m new to buffer overflow exploits. I’m trying to run this code and when giving input instead of the addition function running + run the multiplication function \* using buffer overflow. I have tried multiple different but non prevailed
Buffer overflow exploit the give code to execute multiplication function \* but the operator given is addition function +
The code has undefined behavior for multiple reasons:
you do not test the return values of scanf(), so invalid input will not be detected.
the functions add, sub, mal, div are defined to return an int value but the code does not have return statements.
you pass a 1 byte array for %s which will cause a buffer overflow unless at end of file. Furthermore, &op does not have the expected type for %s. A more reliable way to input the operation is
if (scanf(" %c", op) == 1) {
/* operation was read as a single character */
} else {
/* unexpected end of file or input error */
}
It is very difficult to exploit these flaws to make the code call mal() instead of add(), but here is an example where invalid input will appear to use multiplication instead of addition:
Enter number-1:0+ 1
Enter number-2:Enter an operator (+, -, *, /):
Answer: 0
Related
int main() {
double num1, num2;
char f1;
printf("What to Count:");
scanf_s("%f", &num1);
scanf_s("%c", &f1);
scanf_s("%f=", &num2);
if (f1 = "+") {
printf("%lf\n", num1 + num2);
}
else if (f1 = "-") {
printf("%lf\n", num2 - num2);
}
else if (f1 = "*") {
printf("%lf\n", num1 * num2);
}
else if (f1 = "/") {
printf("%.2f\n", num1 / num2);
}
else if (f1 = "%") {
printf("%lf\n", num1 % num2);
}
else if (f1 = "#") {
printf("%lf\n", num1 ^ num2);
}
else {
printf("Invalid!\n");
}
system("pause");
return 0;
}
mvs said "a value of type "const char* " cannot be assigned to an entity of type "char"
"expression must have integral or unscoped enum type" etc.
You should get way more compiler warnings:
scanf_s("%f", &num1); here you have a parameter type mismatch. For double you need %lf. Fun fact: For printf("%lf\n", num1 + num2); you don't need the extra l as float parameters are passed as double anyway.
Same for scanf_s("%f=", &num2);. In this call you also require the user to enter = after the number.
scanf_s("%c", &f1); The scanf_s function requires an extra argument for %c format specifier: a value of type rsize_t indicating the size of the receiving array
if (f1 = "+") This is an assignment instead of a comparison. Use == instead.
That is also wrong type. "+" is a string while you only want to compare a character. That would be '+'.
As Jabberwocky pointed out, you are using all kind of functions without including the required headers. Don't do this.
printf("%lf\n", num1 ^ num2); What is this expression supposed to do? Bitwise XOR operator (^) is not allowed to be used with double values.
Same with printf("%lf\n", num1 % num2); The module operator mustn't be used with double values.
Additionally, you should always check return value of scanf and related function. Otherwise how would you know about errors?
From the operations that are not valid for double I assume you are supposed to use int instead.
As you do not use the lengh field of scanf_s you couls also use the standard functions instead.
A fixed version of your code could look like this:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(void) {
int num1, num2;
char f1;
printf("What to Count:");
scanf("%d", &num1);
scanf("%c", &f1);
scanf("%d=", &num2);
int result = 0;
bool invalid = false;
if (f1 == '+') {
result = num1 + num2;
}
else if (f1 == '-') {
result = num1 - num2;
}
else if (f1 == '*') {
result = num1 * num2;
}
else if (f1 == '/') {
result = num1 / num2;
}
else if (f1 == '%') {
result = num1 % num2;
}
else if (f1 == '#') {
result = num1 ^ num2;
}
else {
invalid = true;
}
if (invalid)
{
printf("Invalid!\n");
}
else
{
printf("%d\n", result);
}
system("pause");
return 0;
}
I moved the printing into one place. That would make it easier to change type of calculations.
Output (in WSL):
What to Count:3+5=
8
sh: 1: pause: not found
Confusing assignment and equality operator:
Single '=' is used for assigning a value. For example char a = 5;
This assigns a value of 5 to the character variable a.
Double '==' is used for comparison, or checking equality. For example in this case, you have used single '=' in the conditions, which as you now know is an assignment operator. Replace it with a '=='.
Not including the header files:
The functions like printf and scanf are predefined in the header file <stdio.h>. Without including this, your compiler wouldn't recognize what print and scanf means.
Not checking input validity:
When prompting the user for input, always check the return value of scanf. Consider your users stupid, or even hostile who wants to find a way to crash your program. What if I were to enter 'asdf' when you asked for a character and vice versa? Scanf is a powerful function, but it was meant for parsing, not getting input as such.
Confusing '' and " ":
' ' is for a char variable, whereas " " is for a string variable. You've declared f1 as a character variable after main, not a string variable.
Indentation:
The curly braces are not in their right places. And you may as well omit them when the conditions only contain a single line of code.
Format specifier for double variable:
The format specifier for a double variable in the scanf statement is %lf, whereas a %f is used while printing.
You've also included a '=' operator in the third scanf statement. That could also render the program to work improperly.
int main(void)
{
double num1, num2;
char f1;
printf("What to Count:");
scanf_s("%lf", &num1);
scanf_s("%c", &f1);
scanf_s("%lf", &num2);
double resultdivide = num1 / num2;
double resultpow = pow(num1, num2);
double resultplus = num1 + num2;
double resultminus = num1 - num2;
double resultmult = num1 * num2;
if (f1 == '+') {
printf("%.0f\n",resultplus);
}
else if (f1 == '-') {
printf(".0f\n", resultminus);
}
else if (f1 == '*') {
printf("%.0f\n", resultmult);
}
else if (f1 == '/') {
printf("%.2f\n", resultdivide);
}
else if (f1 == '#') {
printf("%.0f\n", resultpow);
}
else {
printf("Invalid!\n");
}
system("pause");
return 0;
}
this is what i've come up with after brainstorming
looks messy but it actually works so im fine with it
but still can't figure out how to add the % function D:
I am just wondering if it is possible to store the basic arithmetic operators (+, -, *, /) inside variables in C. The reason that I need to do this is because I am trying to build a basic calculator program that accepts up to 5 numbers and can do any of these operations on them. Right now the only way that I have been able to come up with to do this is to store the operators inside a char array and then iterate through it using for loops and switch statements to decide what operator to use for each step. It's pretty clunky and doesn't actually work right now and I am not sure why. Also even if it did work, it wouldn't follow order of operations which I need it to do as well.
This is an example of the output of my program:
Enter a number: 4
Enter an operator (+, -, *, /, or =): +
Enter a number: 8
Enter an operator (+, -, *, /, or =): -
Enter a number: 7
Enter an operator (+, -, *, /, or =): *
Enter a number: 9
Enter an operator (+, -, *, /, or =): /
Enter a number: 2
4.00 + 8.00 - 7.00 * 9.00 / 2.00
0.500000
-6.500000
-6.500000
-3.250000
-3.250000
Result: -3.25
[Finished in 24.13s]
The first 9 lines are just taking the input for the numbers and operators, the 10th line prints out the numbers and operators entered in order, the 11th - 15th lines are supposed to print out the result after each operation which you can see are all incorrect, and the final line prints out the result. What do you think might be causing the math to be incorrect?
Here is my code at the moment:
#include <stdio.h>
#include <stdlib.h>
int main() {
double nums[5];
char operators[5];
double result;
int i = 0;
while ((i <= 4) && (operators[i - 1] != '=')) {
/* Getting the user's input */
printf("Enter a number: ");
scanf("%lf", &nums[i]);
if (i == 4) {
operators[4] = '=';
} else {
printf("Enter an operator (+, -, *, /, or =): ");
scanf(" %c", &operators[i]);
}
i++;
}
printf("%.2f %c %.2f %c %.2f %c %.2f %c %.2f\n", nums[0], operators[0], nums[1], operators[1], nums[2], operators[2], nums[3], operators[3], nums[4]);
for (i = 0; i <= 4; i++) {
/* Doing the math */
if (i == 0) {
/* Getting the value of the first two numbers */
switch(operators[i]) {
case '+' :
result = nums[0] + nums[1];
case '-' :
result = nums[0] - nums[1];
case '*' :
result = nums[0] * nums[1];
case '/' :
result = nums[0] / nums[1];
}
printf("%f\n", result);
} else {
/* Iterating through the rest of both arrays and
continuing to perform operations on the result */
switch(operators[i]) {
case '+' :
result = result + nums[i + 1];
case '-' :
result = result - nums[i + 1];
case '*' :
result = result * nums[i + 1];
case '/' :
result = result / nums[i + 1];
}
printf("%f\n", result);
}
}
// Printing out the answer rounded to 2 decimal points
printf("Result: %.2f", result);
return 0;
}
So just to re-iterate my question, is there a way that I could store the operators in a variable as operators instead of chars, which would remove the need for all of the loops, if statements, and switch statements, and if not, what changes should be made to make my code work properly?
P.S. I am only just learning C right now so suggestions for how I should be formatting my code are welcome too.
First the bugs:
while ((i <= 4) && (operators[i - 1] != '=')) {
On the first iteration of this loop i is 0 so operators[i - 1] attempts to read before the start of the array. Reading outside of array bounds is undefined behavior.
The incorrect values you're getting is because there's no break statement between each of your switch cases. Without that, the code "falls through" to the next case. So if the operation is subtraction you do that, then multiplication, then division.
Regarding the operators, you can create functions to encapulate each operator, each with the same signature (i.e. return type and number/type of parameters) along with a matching typedef. Then you can have an array of pointers to these functions, and set them to point to the proper function.
Also, you don't need to have a special case for the first set of operators. Just start from index 1 instead of 0 and initialize the result to the first value.
#include <stdio.h>
#include <stdlib.h>
double op_add(double x, double y)
{
return x + y;
}
double op_sub(double x, double y)
{
return x - y;
}
double op_mul(double x, double y)
{
return x * y;
}
double op_div(double x, double y)
{
return x / y;
}
typedef double (*op_type)(double, double);
int main() {
double nums[5];
char operator;
op_type operators[5];
double result;
int i = 0;
while (i < 5) {
/* Getting the user's input */
printf("Enter a number: ");
scanf("%lf", &nums[i]);
if (i == 4) {
operators[i] = NULL;
} else {
printf("Enter an operator (+, -, *, /, or =): ");
scanf(" %c", &operator);
switch(operator) {
case '+' :
operators[i] = op_add;
break;
case '-' :
operators[i] = op_sub;
break;
case '*' :
operators[i] = op_mul;
break;
case '/' :
operators[i] = op_div;
break;
default :
operators[i] = NULL;
break;
}
}
if (!operators[i]) break;
i++;
}
result = nums[0];
for (i = 1; i < 5; i++) {
if (operators[i-1]) {
result = operators[i-1](result, nums[i]);
printf("%f\n", result);
} else {
break;
}
}
// Printing out the answer rounded to 2 decimal points
printf("Result: %.2f", result);
return 0;
}
I'm making a program in C that is supposed to ask for two numbers and find their LCM and GCF. However, after asking for those two numbers the code just exits with a non-zero status. Link to code here, any help would be appreciated.
#include <stdio.h>
int main()
{
//Declare things
int i;
int num1,num2 = 0;
int foundLCM = 0;
int foundGCF = 0;
//Ask for input
printf("\nEnter a positive integer: ");
scanf("%i", &num1);
printf("\nEnter another positive integer: ");
scanf("%i", &num2);
//Set i to the bigger number
if(num1 >= num2)
{
int i = num1;
}
else
{
int i = num2;
}
//find the GCF
while(foundGCF == 0)
{
if(num1%i == 0 && num2%i == 0)
{
printf("\nGreatest Common Factor: %i\n", i);
foundGCF = 1;
}
i--;
}
//Find the LCM
while(foundLCM == 0)
{
if(i%num1 == 0 && i%num2 == 0)
{
printf("Lowest Common Multiple: %i", i);
foundLCM = 1;
}
i++;
}
//Kill
return 0;
}
You need to remove the redeclarations of i on lines 21 and 27 and simply assign the value of i to num1 and num2 respectively. As it stands, i is not initialized when it is used in increment/decrement, which results in the program crashing.
Also, you'd need to restore i to its initial value after the GCF loop and before the LCM loop. Otherwise, it'll give wrong value in cases where there's no common factor. I'd suggest storing the initial value in some other variable.
See https://repl.it/NKgR/12
Please note that this is not the optimal way to calculate GCF and LCM. You can have a look at Euclid algorithm and implementations for more info.
The variable i is not initialized.
t.c: In function 'main':
t.c:21:7: warning: unused variable 'i' [-Wunused-variable]
int i = num1;
^
t.c:27:7: warning: unused variable 'i' [-Wunused-variable]
int i = num2;
^
t.c:37:7: warning: 'i' may be used uninitialized in this function [-Wmaybe-uninitialized]
printf("\nGreatest Common Factor: %i\n", i);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You should replace int i = num1; by i = num1; Same thing for int i = num2;
So here is my code. Its a school assignment. I had to make a program to calculate the square root of a number using a method the Babylonians developed etc, that's not the important part. What I was wondering is if it's possible to ignore letters in my scanf so that when I input a letter it doesn't go berserk in my terminal. Any help is welcome and greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double root_Approach(double s); // defines the two functions
void ask_Number(void);
int main() {
ask_Number(); // calls function ask_Number
printf("\n\n");
system("pause");
return 0;
}
double root_Approach(double s) {
double approach;
approach = s;
printf("%.2lf\n", s); // prints initial value of the number
while (approach != sqrt(s)) { // keeps doing iteration of this algorithm until the root is deterimened
approach = (approach + (s / approach)) * 0.5;
printf("%lf\n", approach);
}
printf("The squareroot of %.2lf is %.2lf\n",s, sqrt(s)); // prints the root using the sqrt command, for double checking purposes
return approach;
}
void ask_Number(void) {
double number;
while (1) {
printf("Input a number greater than or equal to 0: "); // asks for a number
scanf_s("%lf", &number); // scans a number
if (number < 0) {
printf("That number was less than 0!!!!!!\n");
}
else {
break;
}
}
root_Approach(number);
}
Scanf reads whatever may be the input from the terminal (character or integer)
One way you can do is to check the return statement of scanf whether the read input is integer or not an integer.
Here is the sample code
int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '\n')
printf("failure\n");
else
printf("valid integer followed by enter key\n");
`
this link may be helpful
Check if a value from scanf is a number?
to make things a little cleaner i only included the + , - operators in this calc.
with the help of others from this board i was finally able to get my numbers to add/subtract consecutively.
My Problem(s):
From my understanding, anything i input besides a + , - should give "Not an operation of the function. Try again".
The first error i run into is that i have to input something other than +, - twice in order to get that message. (shouldn't once be enough since it's the first thing being recognized by the computer?).
And after that, what would my return value have to in order to go back to were i previously left off?
EX:
0 + 3
= 3
-1
=2
Fsgdf
Not an operation of funcation. try again
+1
=3
#include <stdio.h>
/* int askYN (const char *prompt) */
double process (void);
int main ()
{
int done = 0;
while (!done)
{
double result;
result = process();
printf("Final Result = %f\n", result);
}
return 0;
}
double process (void)
{
double orig;
double new_number;
char symbol;
orig = 0;
printf("%.2f", orig);
while(1==scanf(" %c", &symbol))
{
scanf("%lf", &new_number);
if(symbol=='+') {
orig+= new_number;
printf("Result is %.2f \n", orig);
}
else if(op=='-') {
result-=num;
printf("The new result is %6.2f", result);
}
else {
printf("Not an operation of the function.\nTry again.");
}
}
}
I think you need to do like first check the symbol (+/-) then if any symbol from above then go for other scanf to get number`. If not any above symbol then you give error message.
For example
while(1==scanf(" %c", &symbol))
{
if(symbol=='+' || symbol=='-')
{
scanf("%lf", &new_number);
//your arithmetic operation according symbol
}
else
{
//your error message
}
}