分段错误 malloc 指针函数

segmantation fault malloc pointers functions

大家好,这是我的代码:

#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(",");
}

它 compile.But 当我 运行 程序它 returns 一个 "segmantation fault (core dumped)" 错误

我知道这意味着我试图访问内存,我没有访问权限,但我不明白程序的哪一部分有缺陷

问题是,您没有分配足够的内存。这行没问题

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

但是这个循环只是为二维数组的一部分分配内存。

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

内存分配应该看起来更像这样...

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

由于 power 的结果是一致的,因此将值存储在变量中并使用它而不是重新计算它是有意义的。它也会使代码更清晰。

您也不需要转换 malloc 的 return 值,因为 C 会为您处理。并且不需要 sizeof(char),因为它保证始终为 1。