printf() changing treatment of variable in C - c

I have a pretty simple function in my program using the secant method to find a root of a function. It works fine with the printf() that's indicated below. But if I comment it out, the loop endlessly repeats. I have no idea why...
I've read about printf changing a variable, but I don't see anything on it changing the storage of the variable. Am I missing something? It's not a great solution to have it print, since the iterates are not important and the function is called millions of times.
double guess1=500.;
double y1=estimater(r,volume,guess1,adm,tm,rr[r]);
double guess2=adm/30.;
double y2=estimater(r,volume,guess2,adm,tm,rr[r]);
int i;
double guess3=0.;
double y3;
double tol =heightTOL;
int secmax=SECANTMAX;
for(i=1;i<=secmax;i++){
guess3=guess2-y2*(guess2-guess1)/(y2-y1);
if(guess3>adm/2.){
guess3=adm/2.;
}
if(guess3<=0.){
guess3=0.;
}
y3=estimater(r,volume,guess3,adm,tm,rr[r]);
y1=y2;
y2=y3;
guess1=guess2;
guess2=guess3;
if(fabs(guess2-guess1)<tol){
break;
}
if(i==secmax){
printf("\nRan out of iterations in height finder\n");
}
printf("%d %f",i,guess3); //THIS ONE HERE!!!!!!!!
}
return guess3;

printf is not changing your data at all. The only way the printf family of functions can have any effect on your data is if you use the %n format specifier (which writes into the variable whose address you pass) or if you're doing something which invokes undefined behavior, like passing the wrong format arguments. You're not doing either of those things here (your format strings are correct), so your bug lies elsewhere.
Check that all your array accesses are in bounds. Try running your code in Valgrind or other validators to try to find memory errors.

Related

warning: passing argument 2 of 'calcFx' makes integer from pointer without a cast

Okay I found the true culprit of my problems, the numbers were scanning in fine for those of you that were here before this edit.
void computeDataPoints(F_SELECT *fsPtr, int n, double points[][n])
{
int ix; // for indexing points, i.e. columns of 2D array
double x; // for incrementing the value of x
double inc; // incrementation value of x
inc = (fsPtr->xf - fsPtr->x0)/(n-1);
x= fsPtr->x0;
// Setup loop that computes the points and stores in 2D array
for (ix=0; ix<NUM_POINTS; ix = ix + 1)
{
points[X_IX][ix]=x;
points[FX_IX][ix]=calcFx(x, &fsPtr->fNumber);
x = x+ inc;
}
}
I have no Idea how to fix this and have done some searching, if anyone knows how to make this pass properly I'd love you forever
I'm just guessing here since there is really to little go on, but I think the situation is this:
You step through your code in your debugger. You stop at the call to scanf, when the debugger cursor is on the scanf line. That means the call hasn't happened yet. You need to step one more time for the scanf call to happen.
Another possibility is that you step past the scanf call, and the debugger cursor is now on the function closing }. Depending on the compiler and its generated code, that might mean that the variable sfPtr has gone out of scope and can not be examined reliably by the debugger.
The solution to both the above situation is to add another statement between the scanf call and the end of the function. For example a simple printf call to print the values:
...
// Select a range of x for plotting
printf("Select range of x for plotting (x0 and xf):");
scanf("%lf %lf", &sfPtr->x0, &sfPtr->xf);
// Print the values just entered
printf("x0 = %f, xf = %f\n", sfPtr->x0, sfPtr->xf);
// The function ends here
}
Besides printing the values, it also gives you an extra step in the debugger to check the values after the call to scanf.
I FOUND IT
points[FX_IX][ix]=calcFx(x, &fsPtr->fNumber);
needs to be
points[FX_IX][ix]=calcFx(x, fsPtr->fNumber);
Thank you to everyone who tried to help me when I was looking in the wrong spot

Returned value depends on how many printf are in the function

I've got a function that takes a matrix of velocities for a bunch of particles and tries to calculate the total kinetic energy of the particles.
It doesn't give me the right value. In order to debug, I added a few printf("value: %e \n", energy) in the function.
And now, the return value depends on how many of these printfs I leave uncommented.
double GetKineticEnergy(int dim, int nParticles, double vel[nParticles][dim], double mass)
{
int i,j;
double sum;
double energy = 0;
for(i=0;i<nParticles;i++) {
sum = 0;
for(j=0;j<dim;j++) {
sum += vel[i][j]*vel[i][j];
}
energy += sum*mass/2;
// printf("energy: %e \n", energy);
}
// printf("total: %e \n", energy);
return(energy);
}
and right after returning to the caller I print the returned value. I get 18.0, 19.0, 21.0, or 24.0, depending on which combination of the printfs I uncomment.
What am I doing wrong?
Update:
In trying to troubleshoot this, I've commented out pretty much everything. The function is reduced to
{
double energy = 123;
return(energy);
}
and the main program is
int main() {
double a;
double vel[5][5];
a = GetKineticEnergy(1, 1, vel, 1);
printf("value: %e \n", a);
}
and I get
value: 0.000000e+00
as output.
Update:
The problem goes away if I hardcode the second dimension of the 2D array double vel[][3]. For the time being, this seems like a useful fix, but I cringe at that type of hardcoding.
It can happen if GetKineticEnergy function is in a different file and prototype is not available. Consider declaring its prototype in main or include required header file.
You have invoked undefined behaviour.
When you are faced with seemingly inexplicable behaviour from a C program, it is typically the result of undefined behaviour. Here are a few potential problems that you should look into:
Compiler warnings
Compilers usually omit many important warning messages by default, and you have to enable those yourself. Compiling with optimizations enabled can also activate some additional warning messages due to the added code analysis. If you're using GCC, you should at a minimum use something like gcc -ansi -pedantic -W -Wall -O2.
Function prototypes
Have you provided correct function declarations (with prototypes) for all the functions in your code? Without a correct declaration of GetKineticEnergy(), the compiler will pass the last argument as int and assume that the return type is int.
Did you #include <stdio.h>? printf() is a variadic function. Variadic functions usually require different calling conventions than normal functions. Calling a variadic function without the correct prototype causes undefined behaviour.
Buffer overflow
Did you allocate enough memory, or specify a large enough size, for the array passed to the function? Are you passing the correct dimensions? Accessing elements beyond the limits of a buffer can cause perplexing results, especially with optimizations enabled.

In C, technical explanation for how %d recognizes variables in a string

I came across an interesting output and I'd to know how the computer is working to produce this. I know that whenever you have %d in a string, you should have a variable to accompany it. When I wrote two %d's and only one variable, I expected that the computer would churn out the same value for the %d's, since it had only one variable to draw on, but for some reason, the %d's returned the value for x and the value for the variable xCubed. I want to know why the program returns xCubed without my writing xCubed at the end of the string. Here's the code:
#include <stdio.h>
int cube(int x);
int main(void){
int x = 5;
int xCubed = cube(x);
printf("Why does this number, %d, equal this number %d?", x);
return 0;
}
int cube(int x){
return x * x * x;
}
Thank you!
Your program invokes undefined behaviour. Anything could happen. Possibly the valued returned from the call to cube happens to lie next to the value of x on the stack. Of course, this behaviour being undefined means that any change to your program, or your compiler options, could result in different behaviour.
In any case, you are expected to supply two values. Do so.
printf("Why does this number, %d, equal this number %d?", x, x);
If you compiled your program with full warnings then the compiler would have warned you of your error. And you could even ask your compiler to treat warnings as errors to stop you committing the mistake.
Your program causes undefined behaviour, so anything is possible. It's some quirk of stack/register layout and calling convention for your platform that gives you the results you see.
That is because xCubed happens to be allocated just after x, which means closer to the printf part of the stack (activation frame).
printf is a vararg function, it has no implicit way of knowing how many arguments it was passed. So, when you call printf with two placeholders but just one value supplied, it will read past the first argument expecting a second and "fall" into the stack of the caller, whose nearest content is exactly xCubed.
Just to be clear: this is the reason why your code exhibits that particular behaviour, not the way it is expected to work. You have a serious bug in your code.
This was by good luck. In effect, it is undefined behaviour.
Obviously, in your case the variable xCubed was put onto stack immediately after the free space. Upon doing the printf() call, x was put immediately before that, and then the address of the format string.
If you compile this program with other optimization settings, your compiler might decide to put xCubed somwhere else, or in a register, or omit it altogether, as its value is never used.

What is the difference between the two locations?

I have a recursive program. When the printf is used in the function, it outputs 123 and when used outside, it outputs 0123 .
#include <stdio.h>
fact(int);
int main()
{
int x=3;
fact(x);
printf("\n");
system("PAUSE");
}
int fact(int y)
{
if (y > 0)
{
fact(y-1);
printf("%d",y);
}
//printf("%d",y);
}
I am not using both the printf at the same time . What difference does the location of this printf statement create?
Since your if condition looks for the values greater than zero, it is working as expected.
When the printf outside that IF block is used, it gets executed even when y is 0, which is not the case for the printf inside the IF block.
fact(int) is called by following sequence,
fact(3)-->fact(2)--->fact(1)--->fact(0)
The last call is fact(0). According to the implementation of fact(int), when 0 is passed in, 0 is printed if printf() is used outsite. 0 is not printed if printf() is used inside.
In fact, all the values passed into fact(int) is printed when printf() is used outsite.
I'd say one reason you didn't see the answer yourself is because your code is sloppy. Here are some complaints:
Your functions have no explicit return statements which are
especially important for understanding recursive code.
system() requires stdlib, but stdlib.h isn't included.
system("PAUSE") is unportable and unnecessary. Actually your code
would not run on my system because of this. See:
http://www.gidnetwork.com/b-61.html
Your question looks like homework, so this one is the homework's fault and not yours: because n! grows so quickly, factorial functions using 'int' for the return type can only calculate n! for 1<=n<=12, which is useless.
Try this exercise: write a one-line factorial function using a single return and a conditional assignment.

function returning optional value

Whenever we call a function returning value why it is not required to catch the value?
consider the following C code,
int main()
{
int i;
scanf("%d",&i);
printf("Value of i is: ",i);
return 0;
}
Here scanf() returns value 1, but as it is not catched in anywhere why didn't the error pops up?
What is the reason to allow such programming?
Primarily because expressions in C also yield values. For example: x = 1; yields the value 1. Sometimes you use that for multiple assignment like x = y = 1;, but more often you don't.
In early C, the void return type hadn't been invented either, so every function returned some value, whether it was generally useful or not (for example, your call to printf also returns a value).
The rules of the language don't make this an error (doing so would lose compatibility with virtually existing code) and since this is common and rarely indicates a problem, most compilers don't warning about it either. A few lint tools do, which has led a few misguided programmers to write things like (void)printf("whatever"); (i.e., casting the unused return to void to signal that it really, truly was intentional when it was ignored. This, however, rarely does any good, and frequently does quite a bit of harm, so (thankfully) it's rarely seen.
Functions that return a value have that functionality for the use and convenience of the programmer. If you aren't interested in the return value, then don't use it.
Do you need the return value in this example? NO. So you have not used that in this case. But in another situation the return value might be important. For example if you want to read as long as some integer in available in input stream, then you can do something like this:
while (scanf("%d", &i) == 1) {
// do something
}
If there is an EOF then this loop will break. Here return value is needed.
So the summary is use return value when needed, and don't use when not needed. Such programming is allowed because both scenario is possible.
A lot of library functions return values you might not think about. Imagine having to use the return value of every printf call! (printf returns the number of characters printed.)
Pretty much every native c function returns a int. scanf and printf included. It would be really annoying if you always had to "capture" it to satisfy the compiler; In a large program you would end up creating thousands of variables just for storing return values that you never look at.
The reason is that C has no other established way of handling errors than by return value. These returned values, that is to say those return to report success or failure, should almost always be checked (unless you're just doodling around or you have a proof that the function will not fail).
Now since return values are also used for other things than returning success/failure information there might be, and are, situations where you will not be interested in the value a function returns, but just the side effects of executing it. In this case forcing the programmer to inspect/bind the returned value would become quite tideous.
Simple: if you don't use the return value, you don't use it.
It is not mandated that you do.
(That said, in a case like this, you should: you have no idea at present whether scanf encountered an error.)
It is not the case that everytime a value is evaluated,& it must be stored or returned,because the value you have obtained may be used by some other functions,to evaluate different kind of things.A value may be a measure...for example consider the following simple programm,where we want to check that the number entered is even or not
'int main()
{
int a;
printf("Enter a number");
scanf("%d",&a);
if(a%2==0)
printf("even number");
else
printf("odd no");
return 0;
}'
here the variable 'a' is not necessarily to be returned,because we just want to check that the number is even or odd...no need of returning

Resources