Valgrind Errors - Conditional Jump or move depends on uninitialised values - arrays

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.

Related

Process terminated with status -1073741819 mid loop?

Beginner in C and running into a problem with a function that initializes an array. Compiled in Code:Blocks 16.01 on Windows 10. Specific code I'm having issues with is:
void initAuction(float auction[2][MAXAUCTIONITEMS]) {
int i;
for (i = 0; i < MAXAUCTIONITEMS; i++) {
auction[1][i] = -1;
printf("\n%f\t%d\n", auction[1][i], i);
};
for (i = 0; i < MAXAUCTIONITEMS; i++) {
auction[2][i] = 0;
printf("\n\n%f\t%d", auction[2][i], i);
}
printf("\n%f\n", auction[2][70]);
return;
}
I've set up print statements to see how far I'm getting before the crash and I make it to the second for loop but it crashes at i=140. If I change the constant (which is equal to 1000) then the highest I can set it to without crashing is i<84 oddly enough. What would cause the termination status -1073741819 mid loop when the first row initialized no problem but row 2 chooses to crash at around i=140.
I've tried searching on google and here and it seems the termination code isn't a very specific code since I've seen solutions from needing a return statement, trying to access something that doesn't exist, etc. Really lost.
The valid indices are auction[0][*] and auction[1][*].
You are setting elements of the array beyond its boundaries: the initial dimension of auction is 2, the only valid values for this index are 0 and 1.
You can fix and simplify the code this way:
void initAuction(float auction[2][]) {
for (int i = 0; i < MAXAUCTIONITEMS; i++) {
auction[0][i] = -1;
auction[1][i] = 0;
}
}
Note that the second dimension is not part of the type of auction, it is ignored by the compiler.

Board game functions

I have made a program to a board game. My problem is a function, so that certain fields transport the player back or forward. Apparently the thing I did doesn't work.
int numbers()
{
int maxscore;
int numbers[10];
maxscore = enter();
srand(time(NULL));
int nonumbers[3] = {0, 1, maxscore}; //to initialize the scores there shouldn't be a badfield
numbers[10] = rand() % maxscore + 1;
if(numbers[10] == nonumbers[3])
{
numbers[10] = rand() % maxscore + 1;
}
return numbers;
}
int badfields = numbers();
if(score[i] == badfields)
{
printf("Player %d. goes 5 fields backwards", playershown);
score[i] = score[i] - 5;
printf("This player is now in %d Field", score[i]);
}
Somehow I have to repeat the process of entering the maximum score.
I won't directly answer the "question" because there is no "question" to be answered. As others have pointed out in the comments, you need to be more specific and provide a proper description of your problem. But I can still provide the following feedback:
It seems to me you don't quite understand arrays and their indexing. For example, this line should give you a segmentation fault error, or at the very least make a comparison with an unknown value:
if(numbers[10] == nonumbers[3])
This is because your nonumbers array has 3 elements, and thus they should be addressed as nonumbers[0], nonumbers[1] or nonumbers[2] (or, in general, as Weather Vane put it in the comments, from nonumbers[0] to nonumbers[array_lenght-1]). nonumbers[3] will access an undefined position in memory. Your problem could be related to this.
Note that neither me nor anybody is going to review your entire code
to find the error. As stated above, please be more specific.
Also, are you sure you got rid of all compiler errors? Because further down your code you have an uninitialized variable i. To be sure you got rid of all potentially nasty errors, open the terminal (I'm assuming you are on linux) and use the following command to compile your program:
gcc *.c -Wall -Wextra -o program
Then run it with:
./program

Function crashing in release mode but runs flawless in debugger

My program crashes on this function on the 7th line, when I call malloc() when I run in release mode I get the `Program.exe has stopped working message, and when I run in debugger, most of the time it succeeds but sometimes I get this message (especially on larger input):
MONOM* polynomialsProduct(MONOM* poly1, int size1, MONOM* poly2, int size2, int* productSize)
{
int i1, i2;
int phSize = 1, logSize = 0;
MONOM* product;
product = (MONOM*)malloc(phSize*sizeof(MONOM));
monomAllocationVerification(product);
for (i1 = 0; i1 < size1; i1++)
{
for (i2 = 0; i2 < size2; i2++)
{
if (logSize == phSize)
{
phSize *= 2;
product = (MONOM*)realloc(product,phSize*sizeof(MONOM));
monomAllocationVerification(product);
}
product[logSize].coefficient = poly1[i1].coefficient * poly2[i2].coefficient;
product[logSize].power = poly1[i1].power + poly2[i2].power;
logSize++;
}
}
mergeSort(product,logSize);
*productSize = sumMonomsWithSamePower(product, logSize);
return product;
}
I understand that I'm dealing with memory errors and problems, but is there any quick way to analyze my code and look for memory errors? I look at my code a dozen of times looking for this kind of errors and found nothing. (I didn't want to post the code here since its 420 lines long).
First of all, if heap corruption is detected on the first malloc, that means it happened earlier (not in this function or on previous pass). So the problem may lie outside this code.
However, the code also looks suspicious to me.
monomAllocationVerification has no size parameter, so it should work on one monom only, yet you call it only once after realloc on pointer to first element, despite having allocated space for quite a few monoms. Please clarify your decision.
It is a bit unclear why sumMonomsWithSamePower should return a size, and thus modify an array to store a value. May be a quirk, but still suspicious.
UPDATE
The problem was in other functions; a few reallocs with wrong size.
I would check the return value of malloc() and use perror() to describe what error has occured. Also here is the documentation for malloc() and perror().
if((product = (MONOM*)malloc(phSize*sizeof(MONOM))) == NULL)
{
perror("ERROR: Failed to malloc ");
return 1;
//perror() will display a system specified string to describe the error it may tell you the error
}
Also do you know the size of MONOM? If not add the following line to your code.
printf("MONOM SIZE = %i\n", sizeof(MONOM));

While loop not behaving as expected

I am working in an assignment and am experiencing some weird stuff. I have this while loop in my program that does not seem to branch into the for loop. I have placed two print statements and only the "1" prints over and over again. Note that this only happens when I compile and run from the linux terminal. Now what seem weird is that if i run the exact same code (while loop plus everything else) in Netbeans it seems to compile and behave as expected. Anyone know what might be wrong. Here is the code. I appreciate your help.
while(strstr(p,string_a)!= NULL)
{
p = trailerp + pholderp;
long int index = strstr(p,string_a) - (p+1); // -1 where it hits
printf("1");
for( i = 0; i <= index; i++)
{
printf("2");
p2[trailerp2] = pholderp[trailerp];
trailerp++;
trailerp2++;
if(i == index)
{
int j;
for(j=0; j <= lenb-1; j++) // insert the new string
{
p2[trailerp2] = string_b[j];
trailerp2++;
}
trailerp++;
}
}
}
Edit: I have found the problem. Netbeans seems to be broken in this OS.
This is because strstr(p,string_a) returns either p or 0 in this part:
long int index = strstr(p,string_a) - (p+1); // -1 where it hits
which results in index < 0 and prevents going into the loop.
You must print both p and string_a immediately before this statement to see what is going wrong there.

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.

Resources