gcc:error in input - c

i am enthusiast and new in programming trying this simple c language code and compile it with gnu compiler. here is my code:
/*simple program:trying to printf string and get a letter*/
#include "stdio.h"
int main()
{
int i=0;
char c;
while(i++<100){
if(i % 2)
printf("%C this is even number",i);
if(i==50){
c=getchar();
printf("you enter %c letter",c);
}
}
return 0;
}
however when i compile it with gcc and run in terminal, it doesnt show anything,no error and no warning. i tried to figure it out by changing the way my code behave but still not work. is it the code that wrong or gcc have bug or may be i miss about something?

Try to put a newline at the end of printf text:
printf("%C this is even number\n",i);
Also i is an int so use the %d format:
printf("%d this is even number\n",i);
Edit: I just tested this with the changes and it works for me.

You should call fflush(stdout) after your display.

It ran for me using cygwin under Windows Vista.
I pasted your code into a file called test.c and ran gcc test.c that output a file called a.exe which I then ran.
johnma#johnma-PC ~
$ ./a.exe
this is even number♥ this is even number♣ this is even number this is even numb
this is even numbern this is even number◄ this is even number this is even numb
er this is even number this is even number↓ this is even numberthis is even numb
er this is even number this is even number! this is even number# this is even nu
mber% this is even number' this is even number) this is even number+ this is eve
n number- this is even number/ this is even number1 this is even number
you enter
letter3 this is even number5 this is even number7 this is even number9 this is
even number; this is even number= this is even number? this is even numberA this
is even numberC this is even numberE this is even numberG this is even numberI
this is even numberK this is even numberM this is even numberO this is even numb
erQ this is even numberS this is even numberU this is even numberW this is even
numberY this is even number[ this is even number] this is even number_ this is e
ven numbera this is even numberc this is even number
johnma#johnma-PC ~

Related

Integer overflow not overflowing?

I'm doing the ctf challenge from 247CTF "impossible numbers".
The challenge is about integer overflow, and consists of the following file:
#include <stdio.h>
int main() {
int impossible_number;
FILE *flag;
char c;
if (scanf("%d", &impossible_number)) {
if (impossible_number > 0 && impossible_number > (impossible_number + 1)) {
flag = fopen("flag.txt","r");
while((c = getc(flag)) != EOF) {
printf("%c",c);
}
}
}
return 0;
}
You can try the challenge at:
$ nc 1765a1cbe1629dfc.247ctf.com 50458
It's pretty simple, you need to trigger this case:
if (impossible_number > 0 && impossible_number > (impossible_number + 1))
Which you do by inputting 2147483647, which then overflows in the line impossible_number + 1.
This works for me, but I have also tried running it locally in vs code, and here the if statement is not triggered.
After doing some debugging, I have concluded that this is the proporsition that fails:
impossible_number > (impossible_number + 1)
This is really weird to me, I have even tried adding some prints of the values:
#include <stdio.h>
int main() {
int impossible_number;
FILE *flag;
char c;
if (scanf("%d", &impossible_number)) {
printf("impossible nr: %d \n", impossible_number);
printf("plus one nr: %d \n",impossible_number + 1 );
if (impossible_number > 0 && impossible_number > (impossible_number + 1)) {
flag = fopen("flag.txt","r");
while((c = getc(flag)) != EOF) {
printf("%c",c);
}
}
}
return 0;
}
which prints this:
impossible nr: 2147483647
plus one nr: -2147483648
This makes no sense to me, why does this work on the 247CTF server, but not when I run it?
As has been noted in the comments, signed integer overflow is undefined behavior in C.
The game's version of the program was apparently built with a compiler that handles it naively: by actually adding 1 to impossible_number (using ordinary two's-complement addition), then comparing the result with impossible_number and executing the fopen if it's less. In that case inputting 2147483647 works, as you saw. In my tests, clang without optimizations behaves like this.
But there are other possibilities. For instance, recent versions of GCC, even with -O0, notice that the test can't be true in any case when overflow doesn't occur. And if overflow does occur, the behavior is undefined, and so the compiler is at perfect liberty to do whatever it likes in that case. So it is allowed to assume that the test can't ever be true, and that's what it does: it optimizes away the entire if block, including the test itself which is now redundant. Try on godbolt; note that the generated assembly contains no call to fopen at all. So this program compiled with GCC is not vulnerable. The same is true for clang if optimizations are enabled (-O1 or higher).
(You can force the "naive" behavior in either compiler by compiling with -fwrapv. There is also -ftrapv which forces the program to abort if signed integer overflow ever occurs; it has a substantial runtime performance cost, but might be desirable when security is critical.)
Thus for an attack like this, you have to not only read the source code of the vulnerable program, but also be able to discover or guess what is in the compiled code that the victim is actually using.

In what situation the output could go wrong like this?

I am trying to do the problem 200B on codeforces. I tested my code, and the output was all right. But when I uploaded it to the online judge system, I failed on the very first test case. It said my output was -0.000000000000, instead of 66.666666666667.
But I have compiled and run on Visual Studio C++ 2010, MacOS clang 13.0.0, and Linux GCC 6.3.0, the outputs were all the same as mine, 66.666666666667. I am very curious and want to figure out in what situation the output could be -0.000000000000.
On my computer,
Input:
3
50 50 100
Output:
66.666666666667
On the online judge system,
Input:
3
50 50 100
Participant's output
-0.000000000000
Jury's answer
66.666666666667
Checker comment
wrong answer 1st numbers differ - expected: '66.66667', found: '-0.00000', error = '1.00000'
#include <stdio.h>
int main(void)
{
int n;
double sumOrange = 0;
double sumDrink = 0;
scanf ("%d", &n);
while (n-- > 0) {
int m;
scanf("%d", &m);
sumOrange += m / 100.0;
sumDrink++;
}
printf("%.12lf\n", (sumOrange / sumDrink) * 100.0);
return 0;
}
I just don't understand why my output could be -0.000000000000. Please help, thanks.
Update: Tested on different versions of GCC (4.9, 5.1, 6.3), the wrong output does not appear. Guess the cause might lie in the specific implementation of printf.
The problem is because printf function in GNU gcc C11 does not support %.12lf format. It should be changed to %.12f For more information, you can read the article below:
Correct format specifier for double in printf

Problem with running and compiling c with Git Bash on Windows

screenshot
I'm fairly new to all of this, so if it is possible could help be really dumbed down for me thank you :).
So I've had about 1 semester of coding at Uni, and we were learning C. Wanting to practice during my holiday I've done some research and opted to download Atom, installed the Gpp-compiler packages, MinGw and created a path, installed git bash etc. according to all the online instructions I could find.
However when I finally thought I was done with all the set up, a problem occured. As I was testing things out, I realised I couldn't run things properly like I was doing on the uni terminal and gedit.
Shown in my screenshot, shouldn't "hello world" be printed first after I try to run it, then I could enter a value and it should print the value or something.
However after running it would come up blank, until I enter something random and then it would print all at once.
Not sure what's happening here or what I did wrong, any guidance would be great thank you.
Edit: this only seems to be a problem, when I use scanf. Without it, everything prints out in order.
My code:
#include <stdio.h>
int main (void) {
int value;
printf("hello world\n");
scanf("%d", &value);
printf("%d", value);
return 0;
}
when I try to call, it comes out blank until I input 45, then it prints out "hello world" "45"
FNATIC P1#PC MINGW64 ~/OneDrive/Documents/CPP
$ gcc -o main main.c
FNATIC P1#PC MINGW64 ~/OneDrive/Documents/CPP
$ ./main
45
hello world
45
Another example:
#include <stdio.h>
#include <math.h>
int main(void) {
double sideA, sideB, sideC;
double s, area;
printf("Please enter 3 sides of your triangle: \n");
scanf("%lf %lf %lf", &sideA, &sideB, &sideC);
s = (sideA + sideB + sideC) / 2;
area = sqrt(s * (s - sideA) * (s - sideB) * (s - sideC));
printf("%lf\n", area);
return 0;
}
Output: nothing came out until I entered (2 3 4) and (5.31 4.2 7.77)
FNATIC P1#PC MINGW64 ~/OneDrive/Documents/CPP
$ ./heron
2 3 4
Please enter 3 sides of your triangle:
2.904738
FNATIC P1#PC MINGW64 ~/OneDrive/Documents/CPP
$ ./heron
5.31 4.2 7.77
Please enter 3 sides of your triangle:
10.542172

Im having problems using stdin and NULL in eclipse

Here is my code that I am having issues with. The goal of the program is to scan in a bunch of doubles and perform some simple statistical operations on them. The line I am having the issue with is the fgets(). I have included the stdio.h, it's just not showing up in the code. My actual question is where are the stdin and NULL giving me issues when I though they were part of the language? The exact error I am getting is that both Symbol stdin and NULL could not be resolved.
/*
* simpleStats.c
*
* Created on: Sep 17, 2018
* Author: David Liotta
*/
#include <stdio.h>
#define BUFSIZE 256
int main(){
double n, max, min, sum, mean;
char line[BUFSIZE];
int numsRead = 0;
int numOfItems = 1;
n = -1;
max = n;
min = n;
sum = n;
while(n != 0 && fgets(line, BUFSIZE, stdin ) != NULL){
numsRead = sscanf(line, "%f", &n);
if(numsRead == 1 && n != 0){
numOfItems++;
if(n > max)
max = n;
if(n < min)
min = n;
sum = sum + n;
}
if(numsRead == 0)
printf("Bad input\n");
}
mean = sum / numOfItems;
printf("# of items: %i", numOfItems);
printf("\nSum: %f.3", sum);
printf("\nMax: %f.3", max);
printf("\nMin: %f.3", min);
printf("\nMean: %f.3", mean);
}
This code should compile. I suspect something might be wrong with your development environment.
Since you're running Eclipse, I'm assuming that your compiler is GCC. I may be wrong though.
Try to locate your compiler executable, and run the compilation by hand:
gcc -Wall -o simpleStats simpleStats.c
or, if you're on Windows:
gcc.exe -Wall -o simpleStats.exe simpleStats.c
You may have to specify the full path to gcc.exe, (depending on your environment, it might even be called something else; you may be able to retrieve the full path from the console window in Eclipse).
Pay close attention to the output. Copy/paste the full output verbatim in your original post if you can (do not rephrase the warnings / error messages).
I seldom use Eclipse, but with most IDEs you get to chose what kind of project you want to create. Make sure you selected something like "console application", the error you're referring to (stdin not being resolved) may suggest a linker error. Again, it's hard to tell without the exact GCC output.
A couple more things to check:
make sure your compiler and its dependencies are properly installed,
make sure that this compiler is targeted at Windows (or whatever OS you use), not at some exotic embedded platform,
most development environments come with a bunch of sample projects, see if you can build one.
The problem I was having ended up being the compiler not correctly reading the code. I used a different compiler, and with some minor syntax changes, the code worked fine.

Debugging C code with gdb

This is a homework assignment, I just want help with gdb, not specific answers.
I have no experience with gdb whatsoever and little terminal experience. I followed a simple example online to debug some code using gdb but in the example gdb pointed out that a problem happened when it ran the code. When I try to mimic the process for this assignment gdb doesn't say anything. I am still somewhat new to C, but I can see problems when I look at the code and gdb isn't saying anything.
Say the file is named test.c, in the terminal I type gcc test.c and it gives me a warning because printf() is there but #include <stdio.h> is not, which is good because that is supposed to be wrong.
It also produces a.out and if I run it in the terminal with ./a.out nothing happens. The terminal just is ready for my next input with no messages. If I type gdb ./a.out and then run it just tells me the program exited normally.
Can someone point out what I have to do to make gdb point to the errors please?
// insertion sort, several errors
int X[10], // input array
Y[10], // workspace array
NumInputs, // length of input array
NumY = 0; // current number of
// elements in Y
void GetArgs(int AC, char **AV) {
int I;
NumInputs = AC - 1;
for (I = 0; I < NumInputs; I++) X[I] = atoi(AV[I+1]);
}
void ScootOver(int JJ) {
int K;
for (K = NumY-1; K > JJ; K++) Y[K] = Y[K-1];
}
void Insert(int NewY) {
int J;
if (NumY = 0) { // Y empty so far,
// easy case
Y[0] = NewY;
return;
}
// need to insert just before the first Y
// element that NewY is less than
for (J = 0; J < NumY; J++) {
if (NewY < Y[J]) {
// shift Y[J], Y[J+1],... rightward
// before inserting NewY
ScootOver(J);
Y[J] = NewY;
return;
}
}
}
void ProcessData() {
// insert new Y in the proper place
// among Y[0],...,Y[NumY-1]
for (NumY = 0; NumY < NumInputs; NumY++) Insert(X[NumY]);
}
void PrintResults() {
int I;
for (I = 0; I < NumInputs; I++) printf("%d\n",Y[I]);
}
int main(int Argc, char ** Argv) {
GetArgs(Argc,Argv);
ProcessData();
PrintResults();
}
Edit: The code is not mine, it is part of the assignment
There are different kinds of errors. Some can be detected by programs (the compiler, the OS, the debugger), and some cannot.
The compiler is required (by the C standard) to issue errors if it detects any constraint violations. It may issue other errors and warnings when not in standards compliance mode. The compiler will give you more error diagnostics if you add the -Wall and -Wextra options. The compiler may be able to detect even more errors if you enable optimizations (-O0 through -O3 set different levels of optimization), but you may want to skip optimizations if you want to single-step in the debugger, because the optimizer will make it harder for the debugger to show you the relevant source-lines (some may be re-ordered, some may be eliminated).
The operating system will detect errors involving traversing bad pointers (usually), or bad arguments to system calls, or (usually) floating-point division by zero.
But anything that doesn't crash the program is a semantic error. And these require a human brain to hunt for them.
So, as Brian says, you need to set breakpoints and single-step through the program. And, as jweyrich says, you need to compile the program with -g to add debugging symbols.
You can inspect variables with print (eg. print Argc will tell you how many command-line arguments were on the run line). And display will add variables to a list that is displayed just before each prompt. If I were debugging through that for-loop in Insert, I'd probably do display J and display Y[J], next, and then hit enter a bunch of times watching the calculation progress.
If your breakpoint is deeply nested, you can get a "stack dump" with backtrace.
next will take you to the next statement (following the semicolon). step will take you into function calls and to the first statement of the function. And remember: if you're single-stepping through a function and get to the 'return' statement, use step to enter the next function call in the calling statement; use next at the return to finish the calling statement (and just execute any remaining function calls in the statement, without prompting). You may not need to know this bit just yet, but if you do, there you go.
From gdb, do break main, then run.
From there, next or step until you find where you went wrong.

Resources