0

i've got these structures:

typedef struct tStimulus_tc
{
    short                Key;
    struct tStimulus_tc *Next;

}Stimulus_tc;

struct Frame_tc
{
    int                   ID;     // Frame ID (0..MAX)
    int                   Count;  // Felt Count
    short                 sSize;  // Stimulus List Size
    Stimulus_tc          *sList;  // Stimulus List

};

if i want to free a "struct Frame_tc" is this enough?

void freeFrame (Frame_tc *fTemp)
{
    free(fTemp);
}

or i need to run throught it's stimulus and free 1 by 1? what's the proper way to free a variable?

Khalil Khalaf
  • 9,259
  • 11
  • 62
  • 104

2 Answers2

2

free() takes a previously allocated block and releases it for reuse. It doesn't know nor care about the contents of the buffer.

While you could write a compiler that recursively frees pointers, this isn't a good idea:

static Stimulus_tc stim;
Frame_tc *fTemp = malloc(sizeof *fTemp);
fTemp->sList = &stim;
fTemp->sSize = 1;
free(fTemp); // if this recursively freed pointers, we would free a static object

Only you know how your structure is constructed, therefore you shoud be the one destructing it. In your case that means walking the linked list and freeing each member.

In C++, it's advisable to use higher level mechanisms, like using a std::vector<Stimulus_tc> or std::list<Stimulus_tc>.

In cases where pointer use is inevitable (your case isn't one), consider using smart pointers. And if you absolutely must manage memory the old way, use type-safe new[]/delete[].

Community
  • 1
  • 1
a3f
  • 8,517
  • 1
  • 41
  • 46
2

In C, if your Stimulus_tc list within the struct Frame_tc wrapper is not a traditional head/tail list (e.g. with the final ->Next = NULL), but with the number of nodes contained in list->sSize, you could do something similar to the following:

/* free all nodes in struct Frame_tc->Stimulus_tc list */
void free_list (struct Frame_tc *list)
{

    Stimulus_tc *iter = list->sList;    /* pointer to iterate list   */
    Stimulus_tc *victim = NULL;         /* pointer to node to delete */
    int n = list->sSize;                /* number of nodes to delete */

    if (iter ==  NULL) {
        fprintf (stderr,"print_list() warning: empty list.\n");
        return;
    }

    while (n--) {       /* free n nodes */
        victim = iter;
        iter = iter->Next;
        free (victim);
    }
}

If you set the final Next pointer to NULL, you can eliminate int n = list->sSize; and simply iterate over the list with while (iter) { ...

If there were additional pointer elements within each node that were allocated, you would simply free those values before free (victim);

Look it over and let me know if you have any questions.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85