Home > other >  Freeing allocated memory of a nested structure
Freeing allocated memory of a nested structure

Time:10-14

I have a nested structure of the format:

typedef struct {
    int sensoridentification;
    double time;
    double velocity;
    double acceleration;
} Packet;

typedef struct{
    int sensor_ID;
    int number_of_messages;
    SensorPacket **messages_from_array;
} Node; 

Already, I have a system in place that will continually allocate memory and add data from stdin to structure members until the string "end" is passed in.

Is there a simple function that I can apply to recursively free the memory that I have allocated to this nested structure, when I receive the keyword "end"?

CodePudding user response:

typedef struct {
    int sensoridentification;
    double time;
    double velocity;
    double acceleration;
} Packet;

typedef struct{
    int sensor_ID;
    size_t number_of_messages;
    Packet messages_from_array[];
} Node; 

As I do not see any reason for double-pointer you can make your life easier and simple use flexible array members. Only one allocation (and free) will be needed .

CodePudding user response:

I'm not familiar with any builtin function that does what you ask, but it isn't complicated as well.

Assuming int number_of_messages is the length of messages_from_array, you can iterate through it and free each element until you reach number_of_messages.

  • Related