简体   繁体   中英

Freeing a struct array in C

I looked for something like this before I posted this post and couldn't find..

I have:

struct foo* fooArray= malloc(sizeof(*fooArray)*5);
struct foo* newFoo = malloc(sizeof(*newFoo));
fooArray[0]=*newFoo;
struct foo* newFoo2 = malloc(sizeof(*newFoo2));
fooArray[1]=*newFoo2;

How do I free each of the elements in fooArray?

free(&fooArray[0]); // Gives me error
free(fooArray[0]); // Doesn't compile

First of all this code

struct foo* fooArray= malloc(sizeof(*fooArray)*5);
struct foo* newFoo = malloc(sizeof(*newFoo));
fooArray[0]=*newFoo;
struct foo* newFoo2 = malloc(sizeof(*newFoo2));
fooArray[1]=*newFoo2;

is invalid.

I think you mean the following

struct foo** fooArray= malloc(sizeof(*fooArray)*5);
struct foo* newFoo = malloc(sizeof(newFoo));
fooArray[0]=newFoo;
struct foo* newFoo2 = malloc(sizeof(newFoo2));
fooArray[1]=newFoo2;

To free only these two allocated elements newFoo and new Foo2 you can write for example

free( fooArray[0] );
free( fooArray[1] );

fooArray[0] = NULL;
fooArray[1] = NULL;

If you want also to free the entire array then you can write

free( fooArray[0] );
free( fooArray[1] );

free( fooArray );
struct foo* fooArray= malloc(sizeof(*fooArray)*5);

when you allocate fooArray, you allocate ONE buffer of size 5 times a struct foo. If you want to hold 5 struct foo's, you are good, but you don't have to malloc the array members:

struct foo* newFoo = fooArray
struct foo* newFoo2 = fooArray + 1;
struct foo* newFoo3 = &fooArray[2]; /* array notation */

..and you can only free them all at once

free(fooArray);

BUT...

If you want a set of 5 pointers The size is wrong, and the data type on the left is wrong.

struct foo* fooArray= malloc(sizeof(*fooArray)*5);

should read:

struct foo** fooArray = malloc(sizeof(struct foo*) * 5);

It is a pointer to 5 pointers. Then your array notation can work for allocation and freeing.

fooArray[0] = malloc(sizeof struct foo);
free(fooArray[0]);

BTW, if you want an "array" to grow and shrink dynamically, you don't wan't an array. you want a Single linked list

Just include a (struct foo*) pointer in struct foo and you can do away with fooArray.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM