Jonathan
Jonathan

Reputation: 53

malloc int array (Segmentation fault)

Why I have a Segmentation fault in the last line? I try to search but not found the solution, can anybody tell me why I have a Segmentation fault?

int **o_position(char **map)
{
    int i;
    int j = 0;
    int k = 0;
    int count = 0;
    int **pos_o = malloc(sizeof(int *));

    for (i = 0; map[i][j] != '\0'; i++) {
        for (j = 0; map[i][j] != '\n'; j++) {
            if (map[i][j] == 'O')
                count++;
        }
    }
    pos_o = malloc(sizeof(int) * (count * 2));
    pos_o[0][k++] = count;
}

Upvotes: 1

Views: 109

Answers (1)

Lavish Kothari
Lavish Kothari

Reputation: 2321

Your pos_o variable (which is a pointer to a pointer variable) stores the base-address of contiguous segment of memory for 1 unit - and here the unit is actually base address of another memory location. (And for this another memory location you are nowhere allocating memory) I think you understand this because you have already written this line int **pos_o = malloc(sizeof(int *)); - (here you are allocating 1 unit by sizeof(int*) for a pointer variable). But nowhere you have allocated memory for variable to which this pointer variable will point to.

Not allocating the memory is not a problem, but referencing the memory location without allocating the memory might result in segmentation fault.

You should have something like pos_o[0]=malloc(sizeof(int)) (I suggest allocating it for only one integer variable as I see your variable k is always 0, and you are accessing only one element). Consider allocating more (appropriate amount of) memory if you have your variable k being modified by some logic that you have not mentioned here.

Read more about segmentation faults from here.

Upvotes: 1

Related Questions