Search code examples
c++carraysdynamicprimitive

is free()'ing dynamically allocated primitive arrays necessary in C?


for example, when calculating the height of a tree, see int *heights = malloc(sizeof(int)...). Its recursive, so if there's a memory leak, it will be big with a large tree. I know the general rule is to use free() for every malloc, but does that apply to dynamically allocated primitive types as well?

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;
    }
}

Solution

  • Aside from the fact that the type of the thing you allocate has no bearing on whether you need to free it, there's no need for the malloc/free at all:

    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;
    }