blackwolf12333
blackwolf12333

Reputation: 3

segfault probably because of pointer problems

I am kinda new to C and I am trying to write a simple snake remake. You can view the source on github: https://github.com/blackwolf12333/Snake

When building there are no warnings or errors in the output. But when I run the executable and hit enter it exit's with "Segmentation fault(core dumped)". I am not a pro yet with pointers, I come from java, and when googling I found that it probably is a problem with pointers.

I have no idea of where it is going wrong because for as far as I know I am doing things right. The problem is when I try to loop through my snake's body_part's.

    void print_snake() {
        int i;
        body_part *next = main_snake.head.next;

        move(main_snake.head.pos.x, main_snake.head.pos.y);
        addch('$');
        for(i = 0; i < main_snake.length; i++) { //TODO: segfaults when 'main_snake.length'(should be this) instead of 'main_snake.length - 1'
            printf("1 part");
            print_body_part(next);
            next = next->next;
        }
    }

That's from the snake.c file in the repository.

I hope you guys can help me, greetings blackwolf12333

Upvotes: 0

Views: 95

Answers (2)

S&#233;bastien Dawans
S&#233;bastien Dawans

Reputation: 4626

If you want to iterate over a chained list, don't use a seperate stop condition. Your i variable and main_snake.length are not necessary. You can replace

for(i = 0; i < main_snake.length; i++) 

with

body_part *next;
for(next = main_snake.head.next; next->next != NULL; next=next->next){
    ...
}

Upvotes: 0

hmatar
hmatar

Reputation: 2429

Before going deep through the code it is obvious that when next becomes null and next->next causes segmentation fault.

In the loop you are starting at a node next to head(main_snake.head.next). Therefore in a list of 4 objects you are processing only 3 objects. In that case iterations should be 3 instead of 4 because main_snake.length counts the head also as shown in the function initialize_snake. That is why you are getting segmentation fault.

Upvotes: 1

Related Questions