0

Just for the record: I spent a while already checking similar questions and trying their proposed answers without success

I am facing a "Segmentation fault" error in runtime with the following C code:

#include <stdio.h>
#include <stdlib.h>

#define ROW_NUM     8
#define COL_NUM     7

typedef struct {
    int matrix[ROW_NUM][COL_NUM];
} screen_type;

typedef struct {
    screen_type *p_screen;
} snake_type;

void fillSnake(snake_type *p_snake);

int main(void) {
    snake_type snake;
    fillSnake(&snake);
    return 0;
}

void fillSnake(snake_type *p_snake) {
    fillWithPointer((screen_type*)p_snake->p_screen);
}

void fillWithPointer(screen_type *p_screen) { //segmentation fault in this method
    for (int col = 0; col < COL_NUM; col++) {
        for (int row = 0; row < ROW_NUM; row++) {
            p_screen->matrix[row][col] = 0;
        }
    }
}

The problem is while filling the array with the method fillWithPointer. Any hints will be more than welcome.

Arcones
  • 3,954
  • 4
  • 26
  • 46

2 Answers2

1

In your main function, snake is never initialized, and so its p_snake member is left as a pointer to some arbitrary location in memory. You then attempt to write to this memory within fillWithPointer, which you are not allowed to do, hence the segmentation fault.

To correct this error, allocate some memory for the snake, either on the stack or the heap. One way to accomplish this would be the following:

int main(void) {
    screen_type screen = {{{0}}};
    snake_type snake = {&screen};
    fillSnake(&snake);
    return 0;
}

Note that since the screen is already zero-initialized, your fillWithPointer functions becomes superfluous.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
Brian61354270
  • 8,690
  • 4
  • 21
  • 43
1

As my understanding according to your code you have to do malloc struct snake_type before passing into method in main method. snake_type* snake = (snake_type*)malloc(sizeof(snake_type));

Fillsnake(snake);

Jahangir
  • 161
  • 2
  • 7
  • Could you please show me how in code? Thank you very much!! – Arcones Feb 16 '20 at 17:45
  • Note that this code snippet exhibits a [poor practice](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) in C and should not be copied verbatim. – Brian61354270 Feb 16 '20 at 17:53
  • Thank you veeery much, even when I've selected @Brian answer, your response also has helped me to understand what was the problem – Arcones Feb 16 '20 at 18:12