Home > database >  Segmentation Fault - malloc 2D array
Segmentation Fault - malloc 2D array

Time:09-16

Trying to create a map for a little game. When initialising the map with 2D arrays using malloc, the main function will run okay when the printMap function is commented out, however when trying to display the map with printMap, it returns a Segmentation fault. Totally lost at why this isn't working. Any help appreciated.

This is work for University, who insist the code is in C89 and I compile with -ansi -pedantic -Wall -Werror.

GAME.C file

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include"random.h"

void createMap(char*** map, int xCoord, int yCoord) {
    int i, j;
    xCoord  = 2;
    yCoord  = 2;
    char** mapArray;

    mapArray = (char**)malloc(yCoord * sizeof(char*));
    for (i = 0; i < yCoord; i  ) {
        mapArray[i] = (char*)malloc(xCoord * sizeof(char));
    }
    for (i = 0; i < yCoord; i  ) {
        for (j = 0; j < xCoord; j  ) {
            mapArray[i][j] = "0";
        }
    }
    *map = mapArray;
}

void printMap(char** map, int xCoord, int yCoord) {
    xCoord  = 2;
    yCoord  = 2;
    printf("%d, %d", xCoord, yCoord);
    int i, j;
    
    for (i = 0; i < yCoord; i  ) {
        for (j = 0; j < xCoord; i  ) {
            printf("%d %d", i, j);
            printf("%c", map[i][j]);
        }
        printf("\n");
    }
}

MAIN.C file

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include "random.h"
#include "game.h"

int main(void) {
    int xCoord = 5;
    int yCoord = 5;

    char** map;

    createMap(&map, xCoord, yCoord);
    
    printMap(map, xCoord, yCoord);
    return 0;

}

CodePudding user response:

The function createMap is incorrectly initializing objects of the type char with pointers of the type char * to which the string literal "0" is implicitly converted in these for loops

for (i = 0; i < yCoord; i  ) {
    for (j = 0; j < xCoord; j  ) {
        mapArray[i][j] = "0";
    }
}

Instead of the string literal you need to use integer character constant '0' as for example

for (i = 0; i < yCoord; i  ) {
    for (j = 0; j < xCoord; j  ) {
        mapArray[i][j] = '0';
    }
}

Another problem is a typo in this loop within the function printMap

for (j = 0; j < xCoord; i  ) {
                        ^^^^

You need to write

for (j = 0; j < xCoord; j  ) {
                        ^^^^
  • Related