Jonny999999 / snake-pp

Development of the game Snake++ using C, C++ and SDL2 for the Software Engineering course as part of our studies.
0 stars 0 forks source link

Segmentation fault when snake reaches certain length #2

Closed Jonny999999 closed 11 months ago

Jonny999999 commented 11 months ago

Tested with ad1dd7f5c356fff93acea649dc1e9aacf8ad9289

crash output

+----------+
|          |
|X      T  |
|          |
|SSSSSSS   |
|S         |
|S   X     |
|S         |
|H         |
|F    O  X |
|        X |
+----------+
[D] game: starting GameCycle 0
[D] game: handling portals...
[I] game: picked up food at x=0 y=8 -> growing, placing food
[D] food: generating random position + verifying min/max distance...
zsh: segmentation fault (core dumped)  ./Snake  
jonnyjr9~/git/snake-pp/build%

steps to reproduce:

option1: play game and collect food until crash

option2: run snakeGrow() and placeFood() for certain count

when running both those functions produces crash! Add this to runGameCycle():

//debug grow and place food automatically
if (cnt==10){
    cnt = 0;
        snakeGrow();
        DELAY(10);
        placeFood();
}
cnt++;

debugging / things tried

effect of start length:

start with length = 2 => crashes at game.snake.length=12 start with length = 4 => crashes at game.snake.length=14 (2 tests) start with length = 12 => crashes at game.snake.length=20 (2 tests)

effect of run duration:

run without picking up food => no crash in 5 minutes

run snakeGrow() repeatedly:

no crash when running snakeGrow() every 5 cycles

run placeFood() repeatedly:

no crash when running placeFood every cycle

comment out complex food placement:

replacing placeFood() content with simple assignment results in no crash! must be food placement algorithm

Jonny999999 commented 11 months ago

Found issue. renderGameToArray() in map.c accesses game.snake.tail[] at invalid position when recently grown.

solution 1 (simple)

swap execution order of snakeGrow(); and placeFood(); in game.c: https://github.com/Jonny999999/snake-pp/blob/ad1dd7f5c356fff93acea649dc1e9aacf8ad9289/src/game.c#L106-L110

solution 2 (clean)

modify snakeGrow() in snake.c at: https://github.com/Jonny999999/snake-pp/blob/ad1dd7f5c356fff93acea649dc1e9aacf8ad9289/src/snake.c#L34-L42 so the element is actually valid

solution 2 (bad)

decrease snake length index at map render (might cause issues with printMap() though): https://github.com/Jonny999999/snake-pp/blob/ad1dd7f5c356fff93acea649dc1e9aacf8ad9289/src/map.c#L26-L30 replace for loop with for (int i = 0; i < snake.length -1; i++)

Jonny999999 commented 11 months ago

fixed with "solution 1" for now in: cf92191177cfeee99b7971d6dd02b3dce027d62d