1

My program crashes once it reaches this function in my code. I printed the arrays in the function that are going in and commented out everything else and they are getting passed correctly. I can't figure out why it crashes here.

The arrays are numbers in ascending order.
Maybe my loops or if statements are not right? I think maybe I'm not correctly changing the value in the array at index "d" when it reaches attackerArmy[d] = '0'; //represent 0 as defeated ?

long int defeatedArmies(long int* attackerArmy, long int* defenderArmy, long int size){

    long int i,j,defeated = 0,d;

    for(i=0;i<size;i++){
        for(j=0;j<size;j++){

        //loop for the highest attack value that is lower than defender
            if(attackerArmy[j] < defenderArmy[i])
                d = j; // save the index where it is highest

            if(attackerArmy[j] > defenderArmy[i])
            //no point in checking unnecessary values
                break;
        }
        attackerArmy[d] = '0'; //represent 0 as defeated
    }

    for(i=0;i<size;i++){
        if(attackerArmy[i] == 0) //count how many defeated armies happened
            defeated++;
    }
return defeated;
}

1 Answer 1

3

Problem
if attackerArmy[j] >= defenderArmy[i] is true, d remains uninitialized causing the undefined behavior when you access its value in attackerArmy[d] = '0';.

Possible fix
Initialize d when you declare it.

ex:

long int d = -1L;
...
if(d != -1L) attackerArmy[d] = '0';
Sign up to request clarification or add additional context in comments.

4 Comments

ah yes, didn't think about that. there's one fix. it doesn't crash so far. But now when I try printing the new array (attackerArmy) where some things could be zeroed out after it leaves the first two loops. It is filled with a bunch of different numbers that weren't in either array before
@Hispazn This sounds like a different problem. Is that new number 48 (0x30)? Did you mean '0' and not 0 or '\0' in line attackerArmy[d] = '0';?
yes :O and can you explain to me the difference between '0' and 0 ? I know \0 is just null character, yes?
@Hispazn '0' is character literal for printable character 0 and its value in ascii table is not zero. (Just like 'a' is printable character a and its ascii values in non-zero). 0 OTOH is integer literal with value 0. '\0' is a nul cahracter literal with value 0 in ascii table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.