How do I make printf() print output in the correct order? - c

I have a simple working function that creates a table logging file information.
However, printf prints my output in the wrong order. I tried using fflush(stdout) to flush the buffer but it didn't change anything.
The function:
void printTable(char *libraryName)
{
printf("%-40s%-30s%-25s%-20s\n", "[File Name]", "[Creation Time]", "[Version]", "[Size]");
fflush(stdout);
printf("%-40s%-30d%-25d%-20f\n", libraryName, getCreationTime(libraryName), getVersion(libraryName), getSize(libraryName));
fflush(stdout);
}
The get functions are defined in a seperate file and give accurate output.
After compilation, the output looks like this:
[File Name] [Creation Time] [Version] [Size]
125 kB
Version: 1.0.0.0 [6-02-2020 03:32:21 PM] Objects.dll
But it needs to look like this:
[File Name] [Creation Time] [Version] [Size]
Objects.dll [6-02-2020 03:32:21 PM] 1.0.0.0 125 kB
What do I need to do to my printf() function to get the correct order output? I've tried flushing the buffer and rearranging order of the functions. Is it possible to get the output in the correct order without writing a separate printf() statement for each function?

The code you posted is fine and flushing isn't the answer. There's no way %d specifier could print strings like [6-02-2020 03:32:21 PM] and Version: 1.0.0.0, nor could %f result in 125 kB.
I suspect your get functions are printing their results rather than returning them, something like:
int getCreationTime(char *libraryName)
{
printf("[6-02-2020 03:32:21 PM] ");
}
int getVersion(char *libraryName)
{
printf("Version: 1.0.0.0 ");
}
double getSize(char *libraryName)
{
printf("125 kB\n");
}
I'm not sure what you are returning. Perhaps nothing? I have the feeling that you've got some compiler warnings you're ignoring. If so, read them, and address them!
If you're wondering why the results are mixed up it's because C doesn't proscribe that function arguments be evaluated in any particular order, such as left-to-right. It looks like getSize is being called first followed by getVersion and getCreationTime. Finally, the printf we see prints libraryName.

Related

Problems with long input/output in C

I have to make a program in C that gets a non-defined amount of double values and prints them all increased by a certain percentage based on the number. The program should stop when the user enters a negative value. It all works well when I use a small quantity of numbers, but when the input consists of a larger amount of numbers the program prints just the last ones.
Here's my code:
#include <stdio.h>
int main()
{
double ins=0; //the input
while(ins>=0){
scanf("%lf",&ins);
if(ins<0){break;}
else{
if(ins<500){printf("%.2lf ",ins*1.15);}
else if(ins<=1000){printf("%.2lf ",ins*1.10);}
else {printf("%.2lf ",ins*1.05);}
}
}
return 0;
}
Additional information: Using GCC compiler.
Example of output the program should give for a specific input.
Input:
4003.31 1212.35 3414.31
4257.1 1394.37 1217.28
3602.85 4218.58 4994.8
1133.82 1086.48 2117.43
2253.86 3827.71 2170.16
1161.27 3069.77 1338.08
2791.99 3709.33 180.43
4555.77 318.58 1912.24
158.68 2106.49 4439.56
1247.34 -0.79
Output I should get:
4203.48 1272.97 3585.03 4469.96
1464.09 1278.14 3782.99 4429.51
5244.54 1190.51 1140.80 2223.30
2366.55 4019.10 2278.67 1219.33
3223.26 1404.98 2931.59 3894.80
207.49 4783.56 366.37 2007.85 182.48
2211.81 4661.54 1309.71
What could I do to make the program work correctly not just with small amounts but also with quantities like the above ?
Edit: the output I'm getting with the above input is "1309.71",which is just the last number of the full output I should receive.
Note: You have a simple logic error. Because you are checking ins<500 before ins<=100 you can never hit the ins<=100 case.
Your code and sample data works for me. Can you give a more detailed description of the problem?
Well, I found out the solution. As you guys said that the code was working properly for you I tested it using another command line interface. And now the output is correct, so it seems like the one I was using before (Windows CMD) was deleting outputted information when that information reached a certain limit, maybe a small buffer size or something like that. Thank you for the help guys !!

VS2010, scanf, strange behaviour

I'm converting some source from VC6 to VS2010. The code is written in C++/CLI and it is an MFC application. It includes a line:
BYTE mybyte;
sscanf(source, "%x", &mybyte);
Which is fine for VC6 (for more than 15 years) but causing problems in VS2010 so I created some test code.
void test_WORD_scanf()
{
char *source = "0xaa";
char *format = "%x";
int result = 0;
try
{
WORD pre = -1;
WORD target = -1;
WORD post = -1;
printf("Test (pre scan): stack: pre=%04x, target=%04x, post=%04x, sourse='%s', format='%s'\n", pre, target, post, source, format);
result = sscanf(source, format, &target);
printf("Test (post scan): stack: pre=%04x, target=%04x, post=%04x, sourse='%s', format='%s'\n", pre, target, post, source, format);
printf("result=%x", result);
// modification suggested by Werner Henze.
printf("&pre=%x sizeof(pre)=%x, &target=%x, sizeof(target)=%x, &post=%x, sizeof(post)=%d\n", &pre, sizeof(pre), &target, sizeof(target), &post, sizeof(post));
}
catch (...)
{
printf("Exception: Bad luck!\n");
}
}
Building this (in DEBUG mode) is no problem. Running it gives strange results that I cannot explain. First, I get the output from the two printf statemens as expected. Then a get a run time waring, which is the unexpected bit for me.
Test (pre scan): stack: pre=ffff, target=ffff, post=ffff, source='0xaa', format='%x'
Test (post scan): stack: pre=ffff, target=00aa, post=ffff, source='0xaa', format='%x'
result=1
Run-Time Check Failure #2 - Stack around the variable 'target' was corrupted.
Using the debugger I found out that the run time check failure is triggered on returning from the function. Does anybody know where the run time check failure comes from? I used Google but can't find any suggestion for this.
In the actual code it is not a WORD that is used in sscanf but a BYTE (and I have a BYTE version of the test function). This caused actual stack corruptions with the "%x" format (overwriting variable pre with 0) while using "%hx" (what I expect to be the correct format) is still causing some problems in overwriting the lower byte of variable prev.
Any suggestion is welcome.
Note: I edited the example code to include the return result from sscanf()
Kind regards,
Andre Steenveld.
sscanf with %x writes an int. If you provide the address of a BYTE or a WORD then you get a buffer overflow/stack overwrite. %hx will write a short int.
The solution is to have an int variable, let sscanf write to that and then set your WORD or BYTE variable to the read value.
int x;
sscanf("%x", "0xaa", x);
BYTE b = (BYTE)x;
BTW, for your test and the message
Run-Time Check Failure #2 - Stack around the variable 'target' was corrupted.
you should also print out the addresses of the variables and you'll probably see that the compiler added some padding/security check space between the variables pre/target/post.

Add debug print code in every function using vim

I have a huge code file and want to insert print code in every function.
I know debugging is one option but I am new to Kernel and kgdb is not an easy and immediate option hence I want to use printf temporarily.
I used vim's multiple buffers to do this task faster, but want to know if there is any way to automate it in .vimrc
Here is what the final code must look like
void foo(int a, int b) {
printf("Some print");
// ...
}
int bar() {
printf("Some print");
// ...
}
void bleh(int b) {
printf("Some print");
// ...
}
one quick way to do it is in the shell:
find -name '*.c' | xargs vim
In vim, you start recording with qq a macro, make use of the global command
:g/\v\s*(void|int) \w+\([^)]*\)/normal A^Mprint("some print");
And then you use the wonderful argdo command:
:argdo normal #q
To save the changes you use:
:argdo normal :w^M
That will add print("someprint") to every function on the located c source code files. If you want to use the function name or the file name in the print statement, you can use the global command with a little complex substitution like (not tested):
:global /\v\s*(void|int) \w+([^)]*)/s/\v(\w+)\([^]]*\)\s* {/\=submatch(0) . '\r\t\tprint(in file.function:'. expand('%') .'.'. submatch(1) . ');'
Remember that ^M and ^[ are not literal strings, they are inserted with <C-v><CR> and <C-v><Esc>
Hope this help

Printf(%s) prints 0

I have this command in my project (in C):
int addFinalDataStr(char* value)
{
fprintf(objFile,"%-7.7s\n",value);
fflush(objFile);
}
When I call this method with the value like: "60100", it prints "60100" with no problems,
but when i call it with a string like "37777777773" it just prints out "0".
I think the your error is caused by the compiler check with another compiler (I recommend you the GCC compiler) and see if it works.
There are 2 issues
printf("%-7.7s\n", "60100");
// should print "60100 ", not "60100" as OP states
printf("%-7.7s\n", "37777777773");
// should print "3777777", not "0".
It appears the compiler is not compliant or something critical is missing from the post.

I have a function with a lot of return points. Is there any way that I can make gdb show me which one is returning?

I have a function with an absurd number of return points, and I don't want to caveman each one, and I don't want to next through the function. Is there any way I can do something like finish, except have it stop on the return statement?
You can try reverse debugging to find out where function actually returns. Finish executing current frame, do reverse-step and then you should stop at just returned statement.
(gdb) fin
(gdb) reverse-step
There is already similar question
I think you're stuck setting breakpoints. I'd write a script to generate the list of breakpoint commands to run and paste them into gdb.
Sample script (in Python):
lines = open(filename, 'r').readlines()
break_lines = [line_num for line_num, line in enumerate(lines) if 'return' in line and
line_num > first and line_num <= last]
break_cmds = ['b %s:%d' % (filename, line_num) for line_num in break_lines]
print '\n'.join(break_cmds)
Set filename to the name of the file with the absurd function, first to the first line of the function (this is a quick script, not a C parser) and last to the number of the last line of the function. The output ought to be suitable for pasting into gdb.
Kind of a stretch, but the catch command can stop on many kinds of things (like forking, exiting, receiving a signal). You may be able to use catch catch (which breaks for exceptions) to do what you want in C++ if you wrap the function in try/finally. For that matter, if you break on a line inside the finally you can probably single-step through the return after that (although how much that will tell you about where it came from is highly dependent on optimization: common return cases are often folded by gcc).
How about taking this opportunity to break up what seems to be clearly a too-large function?
This question's come up before on SO. My answer from there:
Obviously you ought to refactor this function, but in C++ you can use this simple expedient to deal with this in five minutes:
class ReturnMarker
{
public:
ReturnMarker() {};
~ReturnMarker()
{
dummy += 1; //<-- put your breakpoint here
}
static int dummy;
}
int ReturnMarker::dummy = 0;
and then instance a single ReturnMarker at the top of your function. When it returns, that instance will go out of scope, and you'll hit the destructor.
void LongFunction()
{
ReturnMarker foo;
// ...
}

Resources