user786
user786

Reputation: 4364

freeing specific element of struct pointer - C

I have a struct let say

    struct packets {
        int tcp_source;
        int tcp_dest;
        char *ip_source;
        char *ip_dest;
        int seq;
        ...
    } *pkts;

I am allocating space using malloc in while loop and inside while loop when I done using specific pkts (in pointed to by (ptks+index)) I need to free it like this:

    while (i++ < n - 1) {
        (pkts+i)=(struct packets *) malloc(sizeof (struct packets))
        //shared `i` and signal sending thread to send packet
        ...
    }           
    // Now I need to free `(pkts+i)` like
    while (i < 10)
        free((pkts + i)); //Not working
          //OR
        free(pkts[i]); / Not working either -- in both cases error zsh: abort

Question is if I choose to free specific element at time then what is the right way plus what I need if I choose to free all elements at once

Upvotes: 1

Views: 104

Answers (1)

tstanisl
tstanisl

Reputation: 14157

You need to use pkts as an array of pointers to struct packets.

struct packets **pkts = malloc(N * sizeof *pkts);
...
for (int i = 0; i < N; ++i) {
  // setting  i-th element
  pkts[i]=malloc(sizeof pkts[i]);
  // accessing i-th element
  pkts[i]-> ...
}
for (int i = 0; i < N; ++i) {
   // freeing individual element
   free(pkts[i]);
   pkts[i] = NULL; // avoid accidental accessing or re-freeing 
}
// freeing whole array of pointers
free(pkts);

As mentioned in the comments, you probably do not need to allocate each packets individually. Just allocate an array of packets.

struct packets *pkts = malloc(N * sizeof *pkts);
...
free(pkts);

If you use C99-compliant compiler and you have a reasonable bound on the number of packets use VLA.

struct packets pkts[N]; // that's all

Upvotes: 3

Related Questions