0

I have a function "printWorld" in a class that prints a 2D array called "world". Whenever I use this function and run my program in the terminal it appears to print the array but then a massive amount of random numbers and at the end says "Segmentation Fault" and closes my program. As soon as I take this function out of my code though everything works just fine.

void printWorld()
{
    for(int r = 0; r <= (2*WORLD_SIZE + 1); r++)
    {
        for(int c = 0; r <= (2*WORLD_SIZE + 1); c++)
            cout << world[r][c];
        cout << endl;
    }
}

This is how the function is written in the class

game.printWorld();

This is how I'm calling the function.

This is what is showing in termninal

If it helps I have this array initialized all to 0.

4
  • 4
    When people use <= as the condition in a for loop i smell a bug Commented Dec 4, 2017 at 21:31
  • What size is your array? Show us the declaration. Commented Dec 4, 2017 at 21:32
  • 1
    The seg fault is probably because for(int c = 0; r <= (2*WORLD_SIZE + 1); c++) is an infinite loop (assuming the condition is true once, since r never changes in the scope of that loop). Did you mean c <= ...? Commented Dec 4, 2017 at 21:35
  • @Imran answered like that below but then deleted the answer. IT is surely the right answer tho Commented Dec 4, 2017 at 21:39

1 Answer 1

2

As others have already stated, the mistake is the inner for loop where you compare 'r <= (2*WORLD_SIZE + 1)'

This causes an infinite loop.

Change the inner for loop to be:

    for(int c = 0; c <= (2*WORLD_SIZE + 1); c++)
        cout << world[r][c];
    cout << endl;

That should do it for you : )

Sign up to request clarification or add additional context in comments.

Comments

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.