是免费的()动态分配C中必需的原始数组?

Chr*_*ava 1 c c++ arrays primitive dynamic

例如,在计算树的高度时,请参阅int*heights = malloc(sizeof(int)...).它是递归的,所以如果有内存泄漏,它会很大,有一棵大树.我知道一般规则是对每个malloc使用free(),但是这也适用于动态分配的原始类型吗?

typedef struct EQTNode {
    EQPos *pos;
    int genNumber;
    struct EQTNode * parent;
    int numberOfPossibleMoves;
    struct EQTNode ** children;
} EQTNode;

...

int EQTN_getHeight(EQTNode *node, int depth){
    if (node != NULL){
        int n = node->numberOfPossibleMoves;
        int *heights = malloc(sizeof(int) * n);
        for (int i = 0; i < n; i += 1){
            heights[i] = EQTN_getHeight(node->children[i], depth + 1);
        }
        int max = 0;
        for (int i = 0; i < n; i += 1){
            if (heights[i] > max){
                max = heights[i];
            }
        }
        return max;
    } else {
        return depth;
    }
}
Run Code Online (Sandbox Code Playgroud)

raz*_*zeh 5

是.

否则,内存将如何释放?


Jim*_*ter 5

除了你分配的东西的类型与你是否需要释放它没有关系这一事实之外,根本不需要malloc/free:

if (node != NULL){
    int n = node->numberOfPossibleMoves;
    int max = 0;
    for (int i = 0; i < n; i++){
        int height = EQTN_getHeight(node->children[i], depth + 1);
        if (max < height)
            max = height;
    }
    return max;
}
Run Code Online (Sandbox Code Playgroud)