Question

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;
    }
}
Was it helpful?

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

OTHER TIPS

Yes.

Otherwise, how would the memory get freed?

Just in case C99 enables variable length arrays so your code can be rewritten as:

   if (node != NULL){
        int n = node->numberOfPossibleMoves;
        int heights[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;
    } 

In this case you don't need explicitly free it.

But each malloc() call should have corresponding free() counterpart.

Anything that you call with malloc should be free()'d by you explicitly. malloc() just allocates you a chunk of memory, its up to you to tell the OS when you're done using it.

Take a look at the man page for malloc()

enter image description here

C isn't garbage collected, you know ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top