gcc 4.4.4 c89
I have the following code in my channel.h file
typedef struct channel_tag channel_t;
channel_t* open_channel(size_t channel_id);
void close_channel(channel_t *channel);
And in my channel.c file
#include "channel.h"
struct channel_tag {
size_t channel_id;
};
channel_t* open_channel(size_t channel_id)
{
channel_t *channel = malloc(sizeof *channel);
if(channel == NULL) {
fprintf(stderr, "Cannot allocate memory\n");
return NULL;
}
channel->channel_id = channel_id;
printf("Channel [ %zu ] has been created\n", channel->channel_id);
return channel;
}
void close_channel(channel_t *channel)
{
printf("Channel [ %zu ] resources has been released\n", channel->channel_id);
free(channel);
}
The problem is with my main.c file. Here I have a for loop that create 5 channel objects and allocates memory for them. However, if I wanted to free them later in my program, I am not sure how I can get a reference to them. This is only 5 I am testing with. But later it could be up to 300.
int main(void)
{
size_t i = 0;
channel_t *channel = NULL;
for(i = 0; i < 4; i++) {
channel = open_channel(i);
if(channel == NULL) {
fprintf(stderr, "Cannot create channel [ %zu ]\n", i);
}
}
/* Do some stuff with the channels and now free them before the program exists.
However, I need to loop and pass all of them, not just one */
for(i = 0; i < 4; i++) {
close_channel(channel);
}
return 0;
}
Many thanks for any suggestions,
Store the channels in an array as you create them. Make sure you can tell whether the
mallocs worked or not at end of program (hence thememsetin this code).