dimanche 16 mars 2014

freeing structs topic




(E-Mail Removed) writes:

> Hi, if I have:
>
> struct rec2 {
> int i;
> };
> struct rec1 {
> struct rec2 two;
> };
>
> int func1(void) {
> struct rec1 *one;
>
> one = malloc(sizeof(struct rec1));
>
> func2(&one->two);
>
> /* here should I "free(one)" or that would
> scramble func2 or any other damage... */
>
> return 1;
> }
> Thanks in advance.


I don't quite know what you mean by "scramble func2". It has executed
at this point, so freeing an object you passed to it won't affect it.
If you *don't* free the object, you'll have a memory leak in your
program.

I notice that you passed func2() the address of a field in your struct
rec1. If func2() stashed away this pointer for some other code in your
program to use later (in a global, for instance), you'll be trying to
access a free'd object, which will be a bug.





Aucun commentaire:

Enregistrer un commentaire