Why this code gives segmentation fault?

1

Whenever the first line of the map is populated a segmentation fault occurs, I would like to know why.

void newmap(int x, int y , int players){

    int linha,coluna;
    char **map = (char **) malloc(sizeof(char*) * y);
    *map = (char *)malloc(sizeof(char)*x);

    for(linha=0; linha<x; linha++){
        for(coluna=0; coluna<y; coluna ++){

           if(linha == 0 || coluna == 0 || linha == (x-1) || coluna == (y-1)) {
               map[linha][coluna] = '*';
               printf("*");
            }
        }
        printf("\n");
    }

}
    
asked by anonymous 14.08.2018 / 00:44

2 answers

2

I think you want to do it this way:

    /* Alocação dinamica relativamente à parte da linha*/
    char **map = (char **) malloc((sizeof(char*) * x)+1);

    /* Alocação dinamica relativamente à parte da coluna*/ 
    for(linha=0; linha<x; linha++)
        map[linha] = (char *)malloc((sizeof(char)*y)+1);

    for(linha=0; linha<x; linha++)
    {
        for(coluna=0; coluna<y; coluna ++)
        {

            if(linha == 0 || coluna == 0 || linha == (x-1) || coluna == (y-1))
            {
                map[linha][coluna] = '*';
                printf("*");
            }
        }
        printf("\n");
    }

First you have to allocate memory for each line, then for each line you need to allocate memory for the column.

To get a more beautiful code could put the map[linha] =(char*)malloc((sizeof(char)*y)+1); within the first for, getting a code cleaner

Do not forget to do free correctly, cycling to clear each column and then give free to the map.

    
14.08.2018 / 01:00
1

You are not allocating each row, you are allocating the general and then a single row, to allocate each row would have to each of them within the row loop. I do not know if it gives the expected result because the question does not inform this, and the code does not give more indications, maybe I can be optimized, but it would look like this:

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

void newmap(int x, int y , int players) {
    char **map = malloc(sizeof(char *) * y);
    for (int i = 0; i < x; i++) {
        map[i] = malloc(x);
        for (int j = 0; j < y; j++) {
            if (i == 0 || j == 0 || i == x - 1 || j == y - 1) {
               map[i][j] = '*';
               printf("*");
            }
        }
        printf("\n");
    }
}

int main(void) {
    newmap(3, 3 , 3);
}

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

    
14.08.2018 / 01:00