首页 > 解决方案 > 如何摆脱分段错误(核心转储)

问题描述

我是 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], "\0";

    //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], "\0");
        }
        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--;
        }
    }
}

标签: clinuxsegmentation-faultcoredumpgentoo

解决方案


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

char playfield[70][70] 

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

在此处输入图像描述


推荐阅读