如何摆脱分段错误(核心转储)

How to get rid of Segmentation fault (core dumped)

我是 Linux 和 C 的新手。目前我正在尝试创建游戏“机器人”,但现在我遇到了分段错误(核心已转储)。 我用谷歌搜索了它,但因为我是 Linux/C 的新手,所以我不太了解,也不知道什么是正确的,什么是错误的。

如果有人能帮我解决这个问题并给我一些我不必每次都问的提示,那就太好了..

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

int x; //row
int y; //column
int robots;
int walls;
char playfield[0][0];

int main(int argc, char *argv[]) {

    printf("Enter the size of the Y-Axis! It should be bigger that 5 and lower that 75!\n");
    printf("It is recommended that you use uneven numbers!\n");
    scanf("%i", &x);
    if(x > 75 || x < 5) {
        printf("Learn to read!\n");
        exit(0);
    }
    printf("Enter the size of the Y-Axis! It should be bigger that 5 and lower that 75!\n");
    printf("It is recommended that you use uneven numbers!\n");
    scanf("%i", &y);
    if(y > 75 || y < 5) {
        printf("Learn to read!\n");
        exit(0);
    }
    printf("Enter the amount of walls!\n");
    scanf("%i", &walls);
    printf("Now enter the amount of robots!\n");
    scanf("%i", &robots);

    playfield[x][y], "[=10=]";

    //Sets the value of every char in the [][] to '-'
    for (int i = 0; i < x; i++) {
        for (int j = 0; j < y; j++) {
            playfield[i][j] = '-';
        }
    }

    playfield[x/2][y/2] = 'O'; //Gets the spawnpoint of the player
    for (int i = 0; i < x; i++) {
        for (int j = 0; j < y; j++) {
            printf("%c ", playfield[i][j], "[=10=]");
        }
        printf("\n");
    }

    placeObjects(walls, '#');

    return 0;
}

//Spawns walls and robots
void placeObjects(int amountOfObjs, char Obj) {
    int ObjX = rand() % (x + 1);
    int ObjY = rand() % (y + 1);
    for(int i = 0; i <= amountOfObjs; i++) {
        int ObjX = rand() % (x + 1);
        int ObjY = rand() % (y + 1);
        if(playfield[ObjX][ObjY] == '-') { 
            playfield[ObjX][ObjY] = Obj;
        } else {
            i--;
        }
    }
}

数组 playfield 被声明为具有零个元素,因此不允许访问其中的任何元素。

由于 xy 的最大允许值有限,您可以静态分配足够的数组元素。

char playfield[76][76];

xy 的最大允许值为 75,而 ObjXObjY 最多为 xy 分别,所以你至少需要 76 个元素)

另一种方法是根据输入的xy动态分配一些元素。

可以这样做:

char** playfield;

int main(int argc, char *argv[]) {

    /* ... */

    /* allocate buffer for y * x elements */
    char* buffer = malloc(sizeof(*buffer) * y * x);
    if (buffer == NULL) return 1;
    /* allocate buffer for x pointers for each row */
    playfield = malloc(sizeof(*playfield) * x);
    if (playfield == NULL) return 1;
    /* assign pointers to each row */
    for (int i = 0; i < x; i++) {
        playfield[i] = buffer + y * i;
    }

    /* ... */

    /* de-allocate what are allocated (for satisfying checkers like Valgrind) and exit */
    free(buffer);
    free(playfield);
    return 0;
}

您静态声明了 1x1 矩阵 - 并尝试将值设置为大于 1x1。 因此将第 6 行更改为:

char playfield[70][70] 

您还有一些额外的警告 - 也请尝试摆脱它们。 与此同时,这就是我得到的: