lash
lash

Reputation: 756

Does malloc work recursively?

I have a vector of struct a, size not known at compile time.

Every struct a contains a pointer to a vector of a struct b. Length of vector of struct b is not known at compile time.

So if I do this:

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

 struct b {
    int n;
 };

 struct a {
    int n;
    struct b *v;
 };

 int main() {

    struct a *s;
    struct a *ta;
    struct b *tb;

    s = (struct a*)malloc(sizeof(struct a) * 32);
    s->v = (struct b*)malloc(sizeof(struct b) * 32);
    s->n = 1234;
    ((s->v)+1)->n = 5678;

    fprintf(stderr, "%p: %i / %p: %i\n", s, s->n, (s->v)+1, ((s->v)+1)->n);

    ta = s;
    tb = (s->v)+1;

    free(s);
    fprintf(stderr, "%p: %i / %p: %i\n", ta, ta->n, tb, tb->n);

    return 0;
 }

Outputs for example:

 0x1cb3010: 1234 / 0x1cb3224: 5678
 0x1cb3010: -1526330504 / 0x1cb3224: 5678

Does the struct b vector by any chance automagically get freed when there are allocated memory blocks within the same pointer? Or do I have to first free the individual struct b vectors for every item in the struct a vector?

The question on this link has been suggested as a duplicate of this post, but the question here asks about existing features within the free call, instead of asking for advice on how to make a recursive procedure.

Upvotes: 2

Views: 484

Answers (2)

MD XF
MD XF

Reputation: 8129

Short answer: No, you must have a free for every malloc.

Better answer: Still no, but you can write a function to free multiple struct members. Here's an example:

void freeStruct(struct a *foo)
{
    free(foo->v);
    free(foo);
}

Also: Don't cast the return value of malloc.

Upvotes: 4

eyalm
eyalm

Reputation: 3366

For every malloc() you must have a symmetric free().

if you are working in linux environment you can use valgrind to check your program.

run:

valgrind --leak-check=full ./my_prog

and read about your errors

Upvotes: 2

Related Questions