Why is my C program crashing after input? - crash

I am learning to program in C and C++.
My C program keeps crashing after input, here's the code:
\#include\<stdio.h\>
main(){
int n, i,a,sum=0;
printf("How many numbers?\\n");
scanf("%d", &n);
for(i=0;i\<n;i++){
printf("What's the %d number\\n", i+1);
scanf("%d", &a);
sum=sum+a;
}
printf("Sum is %d", sum);
}
And here's the output from my compile log
Compiler: Default compiler
Executing gcc.exe...
gcc.exe "C:\\Dev-Cpp\\Reee.c" -o "C:\\Dev-Cpp\\Reee.exe" -I"C:\\Dev-Cpp\\include" -L"C:\\Dev-Cpp\\lib"
Execution terminated
Compilation successful
There is 0 errors and 0 warnings.
If someone knows how to fix it I would be really thankful.
I tried to make a program that sums up all the numbers in a row. I expected a sum output but the program crashed after input. The program crashes after I input the last number in a row, where it should sum up all of them and output the sum.

I copied this program, added "void" to the main function
and changed the include statement like this ⬇️
everything worked just fine
#include <stdio.h>
void main()
{
int n, i, a, sum = 0;
printf("How many numbers?\\n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("What's the %d number\\n", i + 1);
scanf("%d", &a);
sum = sum + a;
}
printf("Sum is %d", sum);
}
//output:
How many numbers?\n2
What's the 1 number\n4
What's the 2 number\n5
Sum is 9
you should use only one \ when you print somthing.

Related

If else function....how to use return

#include <stdio.h>
#include <cs50.h>
int GetPositiveInt();
int main (void)
{
int min; /*variable to hold minutes*/
printf ("How many minutes does it take you to use a shower?");
scanf ("%d", &min);
int numbtl = min * 12; /*computes number of bottles*/
if (min > 0)
{
printf ("Taking a shower you use %d bottles of water", numbtl);
}
else
{
printf ("Please enter the positive number: \n");
scanf ("%d", &min);}
return min;
}
}
I've written this program but I've got some bug in else place.
Here is the text which I get trying to execute this program.
~/workspace/pset1/ $ make water
clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow water.c -lcs50 -lm -o water
~/workspace/pset1/ $ ./water
How many minutes does it take you to use a shower?0
Please enter the positive number:
10
~/workspace/pset1/ $
Let me explin what I mean by this code and its execution. This code is used to compute how many bottles of water you use while taking a shower. 1 minute of shower equals 12 bottles.
If you enter the positive integer (for example, 10) the result will be like this:Taking a shower you use 120 bottles of water. BUT if you enter 0 or negative integer the program will ask you to enter the positive integer. And here is when the problem occurs. After entering the positive integer I get the result of 0 bottles.
Lets break down your program and see what it is doing; first
int GetPositiveInt();
Is a forward declaration for a function that is never used or defined, you can remove it entirely.
int main (void)
{
int min; /*variable to hold minutes*/
printf ("How many minutes does it take you to use a shower?");
scanf ("%d", &min);
Here we define the main function (the entry point to a c program) and declare a variable of type int called min. Then print out a line asking for user input and read in their response storing it in the min variable.
int numbtl = min * 12; /*computes number of bottles*/
Here you process min by multiplying it by 12 and storing the result in numbtl.
if (min > 0)
{
printf ("Taking a shower you use %d bottles of water", numbtl);
}
Here you check if min is valid, if it is you print the response. Here you can see the success path of your program is correct, the problem is what happens when min is not greater than 0. (Note there was a minor formatting error in this next bit that I corrected by what I assume you meant - note that this is why correct indenting and formatting is important).
else
{
printf ("Please enter the positive number: \n");
scanf ("%d", &min);
}
If min is not valid (ie less than or equal to 0) then you ask for another input and store it in min.
return min;
}
Lastly you return whatever is stored in min. Note you never actually do anything with this second value, except return it.
Side note: The return value on main is used as the exit status of your application. You can see the exit status of the last command in bash with echo $?.
$ ./water
How many minutes does it take you to use a shower?
2
Taking a shower you use 24 bottles of water
$ echo $?
2
This is probably not what you want. The exit status is normally 0 to indicate success and a positive number otherwise. This last return you will likely want return 0 to indicate your program has run successfully.
Now for the logic of your program, what it looks like you are trying to do is obtain some input from the user; validate it (obtaining new input if its invalid); then process it. So the first thing to do is move your processing to the end of your program
int main (void)
{
int min; /*variable to hold minutes*/
...
int numbtl = min * 12; /*computes number of bottles*/
printf ("Taking a shower you use %d bottles of water", numbtl);
return 0;
}
Now we just need to acquire and validate the user input; a typical algorithm to do this is:
prompt for user input
while (input is not valid) {
reprompt for user input
}
process user input
Converting this to c your applications ends up with;
int main (void)
{
int min; /*variable to hold minutes*/
printf ("How many minutes does it take you to use a shower? ");
scanf ("%d", &min);
while (min <= 0)
{
printf ("Please enter the positive number: ");
scanf ("%d", &min);
}
int numbtl = min * 12; /*computes number of bottles*/
printf ("Taking a shower you use %d bottles of water", numbtl);
return 0;
}
This will continue to ask the user for a positive number until they either enter one or hit crtl+c to kill the command. Once a valid number has been obtained it will processes it and print out the result.
#include <stdio.h>
#include <string.h>
int main (void)
{
long min;
char msg[255];
strcpy(msg,"How many minutes does it take you to use a shower?\n");
do {
printf ("%s", msg);
scanf ("%lu", &min);
strcpy(msg , "Please enter the positive number: \n");
}while( min <= 0 );
long numbtl = min * 12; /*computes number of bottles*/
printf ("Taking a shower you use %lu bottles of water", numbtl);
return 0;
}
You can also use a goto label. Here I used a goto label named start. If a number less than zero is entered then the program goes to beginning of the program. Hope, It helps.
#include<stdio.h>
int main (void)
{
int min; /*variable to hold minutes*/
start :
printf ("How many minutes does it take you to use a shower?\nEnter here : ");
scanf ("%d", &min);
if (min <= 0)
{
printf("Enter a number grater than zero\n\n");
goto start;
}
int numbtl = min * 12; /*computes number of bottles*/
printf ("Taking a shower you use %d bottles of water", numbtl);
return 0;
}

Java: Ask user input and divide by those integers

In Java,I need to ask user input for two integers. The program needs to divide by these two integers and produce a decimal to the sixth place.
I know that i will need to name two integers: numerator and denominator. Also, I need to name a double variable: result.
Thanks for the help!!
You haven't given any clues as to the language or platform you are using, but here is a basic example written in C running on a console.
#include <stdio.h>
int main()
{
int num, den;
double quo;
printf("Enter numerator: ");
scanf("%d", &num);
printf("Enter denominator: ");
scanf("%d", &den);
if (den == 0)
printf("Divide by zero\n");
else {
quo = (double)num / (double) den;
printf("Quotient = %.6f\n", quo);
}
return 0;
}

Scanf in Objective C Crashes Xcode And the Program

I have removed scanf from the code and the rest of the program runs with no issue. When the code reaches scanf, and after I type a number, xcode 'loses connection' and displays the error "Program ended with exit code: -1". I have also tried making 'input' an int, changed the name of variable input in case there was a conflict there, and tried it without fflush in the code. I am running Mountain Lion on Oracle VM Virtualbox, and my computer is on Windows 7, if that's relevant.
What am I doing wrong?
#import Foundation/Foundation.h
#include stdio.h
int main(int argc, const char * argv[])
{
#autoreleasepool {
float input = 1;
int i = 0;
float total = 0;
int max = 0;
int min = 1000;
while (input != 0){
NSLog(#"Please put in a number. \n");
scanf("%f", &input);
fflush(stdin);
if(input > max){
max = input;
}
if(input < min){
min = input;
}
total = total + input;
i++;
}
printf("The number of entered numbers was %i \n", i);
printf("The sum of the entered numbers is %f\n", total);
total = total/i;
printf("The average of all the numbers is %f\n", total);
printf("The highest number entered is %i\n", max);
printf("The lowest number entered is %i\n", min);
}
return 0;
}
fflush(stdin);
You probably want
fflush(stdout)
I'm not sure what fflush() will do with an FILE* opened for input.
This may or may not be the cause of your issues.
Return and Enter key have a different meaning inside Xcode. You go to the product menu and select build build for running and execute it in the terminal it will work fine.
Inside Xcode the Enter key in the numpad stops the program with a -1 return code. I am not sure whether this is bug or a feature, but I could not find the key in the keybinding for Xcode.
Please check here

Objective c, Scanf() string taking in the same value twice

Hi all I am having a strange issue, when i use scanf to input data it repeats strings and saves them as one i am not sure why.
Please Help
/* Assment Label loop - Loops through the assment labels and inputs the percentage and the name for it. */
i = 0;
j = 0;
while (i < totalGradedItems)
{
scanf("%s%d", assLabel[i], &assPercent[i]);
i++;
}
/* Print Statement */
i = 0;
while (i < totalGradedItems)
{
printf("%s", assLabel[i]);
i++;
}
Input Data
Prog1 20
Quiz 20
Prog2 20
Mdtm 15
Final 25
Output Via Console
Prog1QuizQuizProg2MdtmMdtmFinal
Final diagnosis
You don't show your declarations...but you must be allocating just 5 characters for the strings:
When I adjust the enum MAX_ASSESSMENTLEN from 10 to 5 (see the code below) I get the output:
Prog1Quiz 20
Quiz 20
Prog2Mdtm 20
Mdtm 15
Final 25
You did not allow for the terminal null. And you didn't show us what was causing the bug! And the fact that you omitted newlines from the printout obscured the problem.
What's happening is that 'Prog1' is occupying all 5 bytes of the string you read in, and is writing a null at the 6th byte; then Quiz is being read in, starting at the sixth byte.
When printf() goes to read the string for 'Prog1', it stops at the first null, which is the one after the 'z' of 'Quiz', producing the output shown. Repeat for 'Prog2' and 'Mtdm'. If there was an entry after 'Final', it too would suffer. You are lucky that there are enough zero bytes around to prevent any monstrous overruns.
This is a basic buffer overflow (indeed, since the array is on the stack, it is a basic Stack Overflow); you are trying to squeeze 6 characters (Prog1 plus '\0') into a 5 byte space, and it simply does not work well.
Preliminary diagnosis
First, print newlines after your data.
Second, check that scanf() is not returning errors - it probably isn't, but neither you nor we can tell for sure.
Third, are you sure that the data file contains what you say? Plausibly, it contains a pair of 'Quiz' and a pair of 'Mtdm' lines.
Your variable j is unused, incidentally.
You would probably be better off having the input loop run until you are either out of space in the receiving arrays or you get a read failure. However, the code worked for me when dressed up slightly:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char assLabel[10][10];
int assPercent[10];
int i = 0;
int totalGradedItems = 5;
while (i < totalGradedItems)
{
if (scanf("%9s%d", assLabel[i], &assPercent[i]) != 2)
{
fprintf(stderr, "Error reading\n");
exit(1);
}
i++;
}
/* Print Statement */
i = 0;
while (i < totalGradedItems)
{
printf("%-9s %3d\n", assLabel[i], assPercent[i]);
i++;
}
return 0;
}
For the quoted input data, the output results are:
Prog1 20
Quiz 20
Prog2 20
Mdtm 15
Final 25
I prefer this version, though:
#include <stdio.h>
enum { MAX_GRADES = 10 };
enum { MAX_ASSESSMENTLEN = 10 };
int main(void)
{
char assLabel[MAX_GRADES][MAX_ASSESSMENTLEN];
int assPercent[MAX_GRADES];
int i = 0;
int totalGradedItems;
for (i = 0; i < MAX_GRADES; i++)
{
if (scanf("%9s%d", assLabel[i], &assPercent[i]) != 2)
break;
}
totalGradedItems = i;
for (i = 0; i < totalGradedItems; i++)
printf("%-9s %3d\n", assLabel[i], assPercent[i]);
return 0;
}
Of course, if I'd set up the scanf() format string 'properly' (meaning safely) so as to limit the length of the assessment names to fit into the space allocated, then the loop would stop reading on the second attempt:
...
char format[10];
...
snprintf(format, sizeof(format), "%%%ds%%d", MAX_ASSESSMENTLEN-1);
...
if (scanf(format, assLabel[i], &assPercent[i]) != 2)
With MAX_ASSESSMENTLEN at 5, the snprintf() generates the format string "%4s%d". The code compiled reads:
Prog 1
and stops. The '1' comes from the 5th character of 'Prog1'; the next assessment name is '20', and then the conversion of 'Quiz' into a number fails, causing the input loop to stop (because only one of two expected items was converted).
Despite the nuisance value, if you want to make your scanf() strings adjust to the size of the data variables it is reading into, you have to do something akin to what I did here - format the string using the correct size values.
i guess, you need to put a
scanf("%s%d", assLabel[i], &assPercent[i]);
space between %s and %d here.
And it is not saving as one. You need to put newline or atlease a space after %s on print to see difference.
add:
when i tried
#include <stdio.h>
int main (int argc, const char * argv[])
{
char a[1][2];
for(int i =0;i<3;i++)
scanf("%s",a[i]);
for(int i =0;i<3;i++)
printf("%s",a[i]);
return 0;
}
with inputs
123456
qwerty
sdfgh
output is:
12qwsdfghqwsdfghsdfgh
that proves that, the size of string array need to be bigger then decleared there.

Create a Fraction array

I have to Create a dynamic array capable of holding 2*n Fractions.
If the dynamic array cannot be allocated, prints a message and calls exit(1).
It next fills the array with reduced random Fractions whose numerator
is between 1 and 20, inclusive; and whose initial denominator
is between 2 and 20, inclusive.
I ready did the function that is going to create the fraction and reduced it. this is what I got. When I compiled and run this program it crashes I cant find out why. If I put 1 instead of 10 in the test.c It doesn't crash but it gives me a crazy fraction. If I put 7,8,or 11 in the test.c it will crash. I would appreciate if someone can help me.
FractionSumTester.c
Fraction randomFraction(int minNum, int minDenom, int max)
{
Fraction l;
Fraction m;
Fraction f;
l.numerator = randomInt(minNum, max);
l.denominator = randomInt(minDenom, max);
m = reduceFraction(l);
while (m.denominator <= 1)
{
l.numerator = randomInt(minNum, max);
l.denominator = randomInt(minDenom, max);
m = reduceFraction(l);
}
return m;
}
Fraction *createFractionArray(int n)
{
Fraction *p;
int i;
p = malloc(n * sizeof(Fraction));
if (p == NULL)
{
printf("error");
exit(1);
}
for(i=0; i < 2*n ; i++)
{
p[i] = randomFraction(1,2,20);
printf("%d/%d\n", p[i].numerator, p[i].denominator);
}
return p;
}
this is the what I am using to test this two functions.
test.c
#include "Fraction.h"
#include "FractionSumTester.h"
#include <stdio.h>
int main()
{
createFractionArray(10);
return 0;
}
In your createFractionArray() function, you malloc() space for n items. Then, in the for loop, you write 2*n items into that space... which overruns your buffer and causes the crash.