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

7
  • 3
    positions[x][y] -> positions[y][x] Commented Apr 5, 2019 at 17:34
  • That isn't a valid solution sadly, I tried it and I got the same problem. Commented Apr 5, 2019 at 17:36
  • 2
    It is definitely a valid part of a solution. If you still have a problem, then it is not in the posted code (mvinch)?. Commented Apr 5, 2019 at 17:36
  • Still the same problem... Commented Apr 5, 2019 at 17:38
  • 2
    See How to create a Minimal, Complete, and Verifiable example. Also a debugger might be of some help. Commented Apr 5, 2019 at 17:39

1 Answer 1

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.

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.