My code returns an unexcpected value - c

Sorry for the generic question but I've come across a behaviour in my code that I can't explain and that I find relevant for further users.
There is the screenshot of my screen when it happend. It's a repeatable error that happend any time my code runs.
screenshot
and there is the text version of it.
My code runs a function
inline static int isInBounds(SDL_Surface* img,int x,int y){
if((x<0)||(x >= img->w)||(y<0)||(y >= img->h) ) return 0;
return 1;
}
I ran my code using gdb and I got the results
(gdb) print isInBounds(surface,x,y)
$1 = 1
(gdb) print y >= surface->h
$2 = 1
I don't get it. If (y >= surface->h) = 1, shouldn't the function isInBounds(surface,x,y) return 0 since the if statement is fulfilled ?

The error solved itself one day when I re-run it. Gods know what happened.

Related

Valgrind Errors - Conditional Jump or move depends on uninitialised values

img of error
Above is an error I have been getting, in relation to this line in my program:
storedData[k] = min(dist[index1][k],dist[index2][k]);
Now here is the surrounding functions to this line:
for(int k = 0; k <arraySize; k++){
if(k!= index1 && k != index2){
if(method == SINGLE_LINKAGE){
storedData[k] = min(dist[index1][k],dist[index2][k]);
} else {
storedData[k] = max(dist[index1][k],dist[index2][k]);
}
}
}
Now after playing around with it for quite a while, I realised that the issue it has is with the incrementing 'k' variable in the for loop. More specifically it is worried that when used as an index in dist, the value returned will be uninitialised. Now in terms of functionality, my program works fine and does everything I want it to do. More notably, I have also initialised this function elsewhere in a helper function which is why this confuses me more. I have initialised all the values from index 0-arraysize which in my head means this should never be an issue. Im not sure if maybe this is caused because its done outside of the main function or something. Regardless it keeps giving me grief and I would like to fix it.
You need to work back from the error to its origin. Even if you are initializing your arrays, it is possible that something is 'uninitializing' them again afterwards. memcheck does not flag uninitialized data when it is copied, only when it affects the outcome.
So in pseudo-code you might have
Array arr;
Scalar uninit; // never initialized
init_array(arr);
// do some stuff
arr[3] = uninit; // no error here
for (i = 1 to arr.size)
store[i] = max(arr[i], arr[i-1]; // errors for i == 3 and 4
There are two things that you could try. Firstly, try some 'printf' debugging, something like
for(int k = 0; k <arraySize; k++) {
if(k!= index1 && k != index2) {
fprintf(stderr, "DEBUG: k %d index1 %d index2 %d\n", k, index1, index2);
// as before
Then run Valgrind without a log file. You should then be able to see which indices cause the error(s).
Next, try using ggbserver. Run valgrind in one terminal with
valgrind --vgdb-error=0 prog args
and then run gdb in a second terminal to attach (see the text that is output in the 1st terminal for the commands to use).
You can then use gdb as usual (except no 'run') to control your guest app, with the additional ability to run valgrind monitor commands.

Segmentation Fault with Recursive Function

I am very new to programming in C, and can't seem to locate the cause of the segmentation error that I have been getting. The program I wrote is as follows:
# include <stdio.h>
# include <stdlib.h>
int recursive(int x){
if(x=0)
{
return 2;
}
else
{
return 3*(x-1)+recursive(x-1)+1;
}
}
int main(int argc, char *argv[])
{
int N = atoi(argv[1]);
return recursive(N);
}
I would appreciate any help.
Thanks a lot
if(x=0){...}
it's wrong
It should be
if(x==0){...}
Note:
if (x = 0)
is the same as:
x = 0; if (x)
This:
if(x=0){
is not a (pure) test, it's an assignment. It works in the if since it also has a value (zero), but it's always false so that branch is never taken, i.e. the recursion never stops.
You should enable all compiler warnings, this is very commonly caught by compilers.
Change if(x = 0) to if(0 == x)
It is a good rule of hand to write 0 == x instead of x == 0 because in case of a typo like = instead of == the compiler will give an error.
The segfault error is from the use of argv[1]. Make sure you call your function with an argument, as follow:
$ ./a.out 6
with a.out the name of your program, and 6 the number you want to apply the function on.
The following line will create a segfault :
$ ./a.out
because the first argument isn't set.
Plus, watch out on the second line : use == instead of =

Window instantly closing when opening compiled .exe in C

I have tried so many things. Running from command line, running from cmd, running with /K, putting system("pause"); getchar(); getch(); before return 0 and I simply can't get it to run. I'm writing in Notepad++, compiling in Cygwin and the window appears blank for the split second it appears (according to my screenshot, it could have been taken too early). Basically I've tried anything I could Google myself to. So I figured it must be something wrong with my code that the debugger doesn't show.
#include <stdio.h>
int main()
{
float lt1, lt2, dmg, x;
lt1=10;
lt2=30;
while(lt2>dmg)
{
while(x>0 || lt2>dmg)
{
dmg=dmg+x*lt1;
x--;
return (dmg);
}
x=x+0.01;
return (x);
}
printf("Horde factor is: %f", x);
return 0;
}
I would appreciate any help I can get, and I hope you will bear over with my inexperience.
You have undefined behavior in your code.
When you declare a local variable without assigning anything to it, its value is indeterminate. Usage of this variable will be undefined behavior until you assign a value to it.
In this case it's the dmg and x variables that causes this problem.
Its because of these statement :
return (dmg); //this ends the code execution .. because you have returned something from main()
x=x+0.01;
return (x); // even this one is wrong
you are exiting the code there and never getting to the printf ..
there should only be one return in main() .. and at the end.
More problems with your code:
you don't initialise dmg and x , but you use them as parameters for while loop
float lt1, lt2, dmg, x; // dmg,x uninitialized
In the outer while loop .. its an infinite loop as you don't do anything to the parameters of that loop to get out of it.
Like I said above .. there should be only 1 return in main()
Maybe instead of returning you should look into break; ( i don't know if thats what you want or not as I don't understand your code )

C programming. Why does 'this' code work but not 'that' code?

Hello I am studying for a test for an intro to C programming class and yesterday I was trying to write this program to print out the even prime numbers between 2 and whatever number the user enters and I spent about 2 hours trying to write it properly and eventually I did it. I have 2 pictures I uploaded below. One of which displays the correct code and the correct output. The other shows one of my first attempts at the problem which didn't work correctly, I went back and made it as similar to the working code as I could without directly copying and pasting everything.
unfortunately new users aren't allowed to post pictures hopefully these links below will work.
This fails, it doesn't print all numbers in range with natural square root:
for (i = 2; i <= x; i++)
{
//non relevant line
a = sqrt(i);
aa = a * a;
if (aa == i);
printf("%d ",i);
}
source: http://i.imgur.com/WGG6n.jpg
While this succeeds, and prints even numbers with natural sqaure root
for (i = 2; i <= x; i++)
{
a = sqrt(i);
aa = a * a;
if (aa == i && ((i/2) *2) == i)
printf("%d ", i);
}
source: http://i.imgur.com/Kpvpq.jpg
Hopefully you can see and read the screen shots I have here. I know that the 'incorrect code' picture does not have the (i/2)*2 == i part but I figured that it would still print just the odd and even numbers, it also has the code to calculate "sqrd" but that shouldn't affect the output. Please correct me if I'm wrong on that last part though.
And Yes I am using Dev-C++ which I've read is kinda crappy of a program but I initally did this on code::blocks and it did the same thing...
Please I would very much appreciate any advice or suggestions as to what I did wrong 2 hours prior to actually getting the darn code to work for me.
Thank you,
Adam
your code in 'that' includes:
if (aa == i);
// ^
printf(...);
[note the ; at the end of the if condition]
Thus, if aa == i - an empty statement happens, and the print always occures, because it is out of the scope of the if statement.
To avoid this issue in the future, you might want to use explicit scoping1 [using {, } after control flow statements] - at least during your first steps of programming the language.
1: spartan programmers will probably hate this statement
Such errors are common. I use "step Over", "Step Into", "Break Points" and "watch window" to debug my program. Using these options, you can execute your program line by line and keep track of the variables used in each line. This way, u'll know which line is not getting executed in the desired way.

find squareroot with a loop

double sqrtIt(double x, double low_guess, double high_guess) {
int n = 10;
int num = 0;
while ( n > 0.000000000000001){
n = n / 10;
while (num < x && low_guess <= (low_guess * 10)){
low_guess = low_guess + n;
num = low_guess * low_guess;
}
}
return low_guess;
}
I've tried to use the code above to find the square root of a number. the function works fine most of the time, but when the number is 2, I get the "There is no source code available for the current location. Show disassembly" error from line num = low_guess * low_guess; I don't know what did wrong, and what does show disassembly do? Thanks
The "no source code available" message may indicate that you are not compiling in debug mode, so your IDE can't do a source-level debug. I think there's probably some confusion here, brought on by trying to deal with an IDE for the first time...
As others have said, you should probably declare n and num to be double, not int.
Probably, once you become more familiar with your development environment (as well as the language), some of these things will sort themselves out.
There are some problems with this function, but this seems to be a very strange error to get from that code. I think you made some other error somewhere else in your program, and that error is then causing this problem.
is there a typo in your code?
low_guess <= (low_guess * 10 ) is always true for non negative number...
Even if it worked it would be pretty inefficient. I guess you wanted to write something like this
double sqrtIt(double x)
{
double guess1, guess2;
guess1=1.0;
do
{
guess2=x/guess1;
guess1=(guess1+guess2)/2;
}
while (abs(guess1,guess2)<0.0000001);
return guess1;
}

Resources