Search code examples
carrayspointerssegmentation-faultcoredump

segmantation fault malloc pointers functions


hello guys this is my code :

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

int power(int a, int b) {
    int exponent = b, result = 1;
    while (exponent != 0) {
        result = result * a;
        exponent--;
    }
    //printf("%d",result);
    return result;
}

int fill_it(char ** p, int N, int fliptimes, int column2) {
    if (N < 0) return 0;
    int counter = 0, l;
    char a = 'H';
    for (l = 0; l < power(2, fliptimes); l++) {
        p[l][column2] = a;
        counter++;
        if (counter == (power(2, N) / 2)) {
            counter = 0;
            if (a == 'H') a = 'T';
            if (a == 'T') a = 'H';
        }
    }
    fill_it(p, N--, fliptimes, column2++);
}

int main() {
    int i, fores, j, l, m;
    char ** p;
    printf("how many times did you toss the coin?:");
    scanf("%d", & fores);
    p = (char ** ) malloc((power(2, fores)) * sizeof(char * ));
    for (i = 0; i < fores; i++)
        p[i] = (char * ) malloc(fores * sizeof(char));
    fill_it(p, fores, fores, 0);
    for (l = 0; l < power(2, fores); l++) {
        for (m = 0; m < fores; m++) {
            printf("%c", p[l][m]);
        }
    }
    printf(",");
}

it does compile.But when i run the program it returns a "segmantation fault (core dumped)" error

i know it means that i tried to access memory,i dont have acces to but i dont understand which part of the program is defective


Solution

  • The problem is, you're not allocating enough memory. This line is fine

    p = (char ** ) malloc((power(2, fores)) * sizeof(char * ));
    

    but this loop is only allocating memory for part of the 2-dimensional array.

    for (i = 0; i < fores; i++)
        p[i] = (char * ) malloc(fores * sizeof(char));
    

    The memory allocation should look more like this...

    foresSquared = power(2, fores);
    p = malloc(foresSquared*sizeof(char *));
    for (i = 0; i < foresSquared; i++)
        p[i] = malloc(fores);
    

    Since the result of power is going to be consistent, it makes sense to store the value in a variable and use that rather than recalculating it. It'll make the code clearer too.

    You also don't need to cast the return value of malloc as C handles that for you. And sizeof(char) isn't needed as it's guaranteed to always be 1.