0

When I compile my code with GCC and then I run it, when I call my function into my code, it prints out: "Segmentation fault (core dumped)".

I tried searching on google for solutions.

Here is my current code:

char ** saveLevelPositions() {
  int x, y;
  char ** positions;
  positions = malloc(sizeof(char *) * 25);

  for (y = 0; y < 25; y++) {
    positions[y] = malloc(sizeof(char) * 100);

    for (x = 0; x < 100; x++) {
      positions[x][y] = mvinch(y, x);
    }
  }

  return positions;
}

I expected the function to just run properly and it just gives a segmentation error.

EDIT: For a little bit of context, here is a link to the GitHub project: https://github.com/xslendix/rogue

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Slendi
  • 157
  • 1
  • 13

1 Answers1

5

As other answers and comments indicated, you should swap your use of x and y, so
positions[x][y] should be positions[y][x].

Also, you are not using the correct type to store the result of mvinch. In curses.h it says:

typedef unsigned long chtype;

so you should allocate memory as follows:

chtype ** positions;
positions = malloc(sizeof(chtype *) * 25);
positions[y] = malloc(sizeof(chtype) * 100);

And turn warnings of your compiler on, because the compiler should have flagged this error.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41