Process terminated with status -1073741819 mid loop? - c

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.

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.

Loop through array, find zero, perform action, stop

I am relatively new at programming, and I'm having trouble figuring out how to loop through an array until the counter finds zero, and when it finds zero once, performs an action and exits the loop. Here is the loop I have so far:
for (int i = 0; i<13; i++)
{
if(pHand[i] == 0)
{
pHand[i] = deal(numArray);
printf("%d\n", i);
printHand(pHand, "Your");
}
}
Currently, this loops through the array until it finds zero, calls deal(), prints the value of pHand, and then loops back through the same sequence until i=0. Please help. I am completely stumped on how to fix this.
The break statement can be used to exit an enclosing loop (e.g., a while, do-while, or for) or switch.
for (int i = 0; i<13; i++)
{
if(pHand[i] == 0)
{
pHand[i] = deal(numArray);
printf("%d\n", i);
printHand(pHand, "Your");
break;
}
}
// code will continue executing here if the for loop condition becomes
// false (i is 13) or if the break statement is reached.
In your code, if you encountered ZERO value cell, you just call "deal" function and printf, but you don't exit the loop, your are continuing to the next iteration.
In order to exit the loop, add "break" statement in the "if" scope and you will go out the loop once you fulfill the condition.
Some consider break to be harmful. I've used it plenty, but some people have issues with it. If you wanted to avoid using break, you could do the following:
int i = 0;
char finished = 0;
while (i < 13 && !finished)
{
if(pHand[i] == 0)
{
pHand[i] = deal(numArray);
printf("%d\n", i);
printHand(pHand, "Your");
finished = 1;
}
i++;
}
You could also rework it to use do-while. Some would say that this kind of solution is a little nicer, semantically.

Switching the status of a state machine from inside a loop

I have an array (nchar[12]) and I wrote this code to print it as vertical columns composed of "X"'s.
I first wrote a version with an accumulator and a while-loop and it worked fine, but it only could print colums as long as a given limit.
Then I tried to write it as a state machine, but the output is just an endless series of blank spaces.
I declared status as an int and assigned a value of 1 to it, then:
while (status = 1) {
for (i = 1; i <= 12; ++i) {
status = 0;
if (nchar[i] > 0) {
printf(" X");
--nchar[i];
status = 1;
}
else
printf(" ");
}
It should stop when it doesn't find any value to print for the last processed line, but it just goes on forever and I don't understand why.
The loop never ends because = is the assignment operator not == which is the comparision operator. You probably want
while (status == 1)
Or simply
while (status)
instead of
while (status = 1)
Also if you have an array declared as
type nchar[12];
then the valid indices for it start from 0 and end at 11. So, your loop should start with i=0 and should loop until i<12 becomes false.

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.

Resources