Program Execution not Occuring in Expected Sequence - c

I am using Eclipse (the latest version) along with Cygwin GCC (I have also observed the same issue while using MinGW GCC, and hence changed the GCC).
Consider a simple code snippet:
#include<stdio.h>
int main(){
char a[5];
printf("prompt1\n");
scanf("%s",a);
printf("\Hi\t%s",a);
}
The image shows the entire output of the program, which, as you can see, should be in a completely different order.
This issue was also on my old laptop (same version of Eclipse, with MinGW). However, I have (obviously) never come across this issue on an older version of Eclipse.
(The snippet has a different prompt text..but you get the jist of it)
EDIT: also occurs with the gets() function (but gets, and scanf are obviously displayed in the correct sequence)

printf uses stdout, it's a buffered file stream. It means, it sends data to the output after its internal buffer is full (the buffer size is 512 bytes or some another value). To dump data to the console immediately, use the function fflush before scanf.
#include<stdio.h>
int main(){
char a[5];
printf("prompt1\n");
fflush(stdout);
scanf("%s",a);
printf("Hi\t%s",a);
}

I saw another SO post where Cygwin didn't flush stdio when needed. Adding the following line before the scanf call should fix it.
fflush(stdout);

Related

Linux C console application not using previous command on "keyup"

I've got the following issue:
int main(int argc, char **argv){
while(1){
char command[25];
scanf(" %25[^\n]s", command);
printf("Command '%s'\n", command);
}
return 0;
}
Now whenever I type something in the console it prints me a message with what I just typed.
But if I use the arrow up key to get the last command out of the memory, the command being sent is
^[[A
Which results in the cursor being moved up by the program.
Now how do I fix this?
I want that the last command from memory is triggered.
Thanks in advance!
This is actually pretty non-trivial thing you are asking for. Luckily, there is a library to fix it: GNU Readline library. Be aware about its licensing, though. Last I heard, it's actual GPL and therefore your own program needs to be that, too, if you use it. NetBSD has a library called libedit, which seems to claim to do much of the same thing with less restrictive license.
Here are some more help with readline: https://eli.thegreenplace.net/2016/basics-of-using-the-readline-library/
And if you can stomach the idea of not integrating it directly into your own program, there is a handy utility program called rlwrap, which provides the end-user at least some of the goodness transparently.

Why does mingw-gcc allow getch() to be used unconditionally?

I recently started porting a TON of my C programs to a Windows environment, from my previous Linux development PC. I noticed something a bit off about mingw's Windows GCC implementation.
In Windows, I found a lovely function called getch. It's easy, it's immediate... and it's also non-standard.
I'd like to focus of the "non-standard" part of it. Specifically, I want to know why mingw-gcc allows me to use it, without using anything but the standard libraries.
Assume we have a program that prints "Hello, World!", a NL and CR, and then waits for a key and a return:
#include <stdio.h>
int main(void)
{
char str[14] = "Hello, World!"; //13 characters and a terminator
printf("%s\n\r", str);
scanf("%c");
return 0;
}
Now, let's change a bit of that program to use getch:
#include <stdio.h>
int main(void)
{
char str[14] = "Hello, World!"; //Again, 13 characters and a terminator
printf("%s\n\r", str);
getch(); //See? now it uses getch.
return 0;
}
The interesting part is, Isn't getch a call made by the conio.h library for old DOS/Win32 environments? The compiler doesn't even give a warning. Why does this work?
Here's something I find even a bit more unsettling:
int main(void) //literally NOTHING included
{
getch();
return 0;
}
What on earth? I know for a fact that getch does not exist on Linux environments (natively, anyways). So, where is the compiler getting this call from?
My best guess (please correct me if I am wrong) is that the decision to link whatever has getch is made at link time, not compile time.
In any case, this seems a little odd to me. Why does an implementation of GCC automatically include clearly non-standard capability on Windows?
The compilation step works (though it should produce a warning) because, traditionally, C allows you to call functions that haven't been declared, provided that they return an int which getch() does.
The linking step works because the C runtime library that MinGW uses is a single library, i.e., it provides all the Visual C runtime library functions, including the non-standard ones. MinGW presumably links with it by default because (apart from very rare edge cases) it is always needed, even if all you want is a main() function that does nothing. :-)
It should also be mentioned that the library in question does not officially support third-party use, except by applications built in Visual Studio 6. The more modern runtimes have deprecated getch in favour of the equivalent but standards compliant _getch, but VS6 predates that change.
The compile step will probably 'work' because compilers (at least older versions of compilers — we know that Visual Studio is not up to date with the latest C standards) will assume the return type and the parameters are all int.
The link step will need the appropriate library linked in.

alternative to the fscanf()/vscanf() functions family for using an alternative validation key or how to create a custom language layout?

I am rather knew in C. And the only way I know for setting a variable from stdin is by using thefscanf()/vscanf()functions family.
DOS operating systems are seeing a resurgence in the embedded market. The device which I am using is programmatically compatible with DOS and use a NEC V30Mx which feature the 80286 instruction set.
The problem is the built-in keyboard doesn’t feature the enter key and instead use the EXE key which enter the 0x1C00 key code (Alt enter).
So when I write a program like this :
#include <stdio.h>
#include <dir.h>
#include <dos.h>
int main(void) {
int res, number = 0;
printf("int value?");
res = scanf("%d", &number);
printf("The value is %d", number);
return;
}
scanf()is called and "int value?" is displayed on the screen. I can write numbers and upercase letters. but I can’t validate the output since nothing feature the 0x1C0D key code, and the EXE key use a different keycode.
Of course C has no knowledge of keyboard but the C standard library binaries look for the 0x1C0D key code for entering a\n.
So is there an alternative to thefscanf()/vscanf()functions family which is part of the C standard library?
Update :
I thought most C standard libraries under dos use software implementation for doing this.
I saw a DOS call for reading files and of course, using the number 0 cause to read from stdin.
So I assembled this example, loaded it on the calculator and find myself surprised the manufacturer preferred handling the issue in it’s built-in software rather than fixing the OS... :-( (I got the the same previous result)
Update
I didn’t thought about it but thanks to the comments, I forgot keyboard languages do key code remapping.
So, creating a custom mapping for the qwerty keyboard would be an another way to solve the problem.
The problem is scanf does not read past the bytes present in stdin that represent the EXE key.
Can you investigate to see what actual characters are read by getchar() when you press the EXE key, and write a function hasexe() that skips these if present. Call this function before or after the scanf().
Also check scanf() return value and check for EOF.
The only way to solve such a problem with standard C library is to use getchar() (or fgetc() on stdin) to get a character one at a time, detect the EXE key yourself, NUL terminate the string and pass it to sscanf().

debugging C with eclipse and cygwin

I am trying to debug the following C code with eclipse-Juno-CDT, and cygwin-gcc (cygwin version=1.7.16, gcc version=3.4.4, gdb version=7.5.50), on 64bit windows. The code works fine in normal mode. Initially debugger was not running, because the source file was not found. Then I searched around and added the path mapping information (from /cygdrive/c to C:\). Now it is running but with the following problems:
I have put a breakpoint before the "hello c 1" line, and then single stepping. But nothing gets printed on the console.
after single stepping on the last line ("exit"), I get the error: "No source available for _cygwin_exit_return() at ..."
// stdio.h and stdlib.h are included, but when I put a #include the code
// they dont show up, so I deleted those lines in this code fragment.
int main(void) {
int a=10;
int b=5; // breakpoint on this line, single step after this
printf("hello c 1\n"); // these outputs are not printed in console
// fflush(stdout);
printf("A=%d, B=%d\n", a, b); // but debugger shows the correct values in data window
// fflush(stdout);
return EXIT_SUCCESS; // error on this line
}
Added later: After some more debugging, I figured that even after the exit-error, if I do a "continue", then I am getting the lines on the console after the program terminates. So I added extra "fflush(stdout)" lines, and now I can see the outputs when they are being printed.
But how to fix the exit-error problem? Also, editing the file to add fflush to see debug outputs is a pain - is there a way to avoid this? Can somebody help me with this very basic problem, or point me to a place where the solution is given? Thanks in advance.
While logically a C program begins at int main() and ends when that function returns, environments (like Windows or Cygwin) frequently add pre- and post-code, for initializing / breaking down memory management, opening / closing standard streams, and other such bookkeeping. An executable compiled with Cygwin, after returning from int main(), switches to a cleanup function _cygwin_exit_return(), provided by the Cygwin runtime - for which you don't have sources, so your debugger complains.
As for getting the output immediately, you could use an unbuffered output stream.
Option one, use fprintf( stderr, ... ) (since stderr is by definition unbuffered). This, however, also affects the non-debugging behaviour of your program.
Option two:
int main()
{
// Using NDEBUG as also used by <assert.h>; feel free to use a different define
#ifndef NDEBUG
// For debugging, set stdout to unbuffered
setbuf( stdout, NULL );
#endif
....
Back when I was learning multithreading I was curious if threads were any faster than processes, and iirc I had to fflush even stderr/stdout on windows.
Memories aside, you can wrap those printf() in a function that calls fflush, or call setvbuf() to disable buffering.
About the exit: "no source available" only means that a part of your program lacks the info for debugging, so it's not a real error -- unless you build cygwin yourself, I guess the cygwin dll is stripped of debug symbols. Or maybe you want to debug cygwin's exit()?
EDIT: crap, concurrent answers :)

Equivalent to Windows getch() for Mac/Linux crashes

I am using getch() and my app crashes instantly. Including when doing:
int main()
{
getch();
}
I can't find the link but supposedly the problem is that it needs to turn off buffering or something strange along those lines, and I still want cout to work along with cross platform code.
I was told to use std::cin.get(), but I'd like the app to quit when a key is pressed, not when the user typed in a letter or number then press enter to quit.
Is there any function for this? The code must work under Mac (my os) and Windows.
Linking/compiling is not an issue; I include <curses.h> and link with -lcurses in XCode, while Windows uses <conio.h>.
Have you looked in <curses.h> to see what the getch() function does?
Hint: OSX and Linux are not the same as Windows.
Specifically, as a macro in <curses.h>, we find:
#define getch() wgetch(stdscr)
Now, there appears, on your system, to be an actual function getch() in the curses library, but it expects stdscr to be set up, and that is done by the curses initialization functions (initscr() and relatives), and that is signally not done by your code. So, your code is invoking undefined behaviour by calling curses routines before the correct initialization is done, leading to the crash.
(Good hint from dmckee - it helped get the link line out of acidzombie24, which was important.)
To get to a point where a single key-stroke can be read and the program terminated cleanly, you have to do a good deal of work on Unix (OSX, Linux). You would have to trap the initial state of the terminal, arrange for an atexit() function - or some similar mechanism - to restore the state of the terminal, change the terminal from cooked mode into raw mode, then invoke a function to read a character (possibly just read(0, &c, 1)), and do your exit. There might be other ways to do it - but it certainly will involve some setup and teardown operations.
One book that might help is Advanced Unix Programming, 2nd Edn by Mark Rochkind; it covers terminal handling at the level needed. Alternatively, you can use <curses.h> properly - that will be simpler than a roll-your-own solution, and probably more reliable.
You have not exhibited a
#include <stdio.h>
or
#include <curses.h>
or similar line. Are you sure that you are linking against a library that includes getch()?
Use the cin.get() function for example:
#include <iostream>
using namespace std;
int main()
{
char input = cin.get();
cout << "You Pressed: " << input;
}
The program would then wait for you to press a key.
Once you have, the key you pressed would be printed to the screen.
The getch function is not available on Unix-like systems, but you can replace it with console commands through your compiler with the system function.
Usage:
In Windows you can use system("pause");
In Unix-like systems (such as OSX) you can use system("read -n1 -p ' ' key");
Note: system is declared in <stdlib.h>.

Resources