c - Allocating and free object of structures -
gcc 4.4.4 c89
i have following code in 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 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 main.c file. here have loop create 5 channel objects , allocates memory them. however, if wanted free them later in program, not sure how can reference them. 5 testing with. later 300.
int main(void) { size_t = 0; channel_t *channel = null; for(i = 0; < 4; i++) { channel = open_channel(i); if(channel == null) { fprintf(stderr, "cannot create channel [ %zu ]\n", i); } } /* stuff channels , free them before program exists. however, need loop , pass of them, not 1 */ for(i = 0; < 4; i++) { close_channel(channel); } return 0; }
many suggestions,
store channels in array create them. make sure can tell whether malloc
s worked or not @ end of program (hence memset
in code).
channel_t **channel = malloc(5 * sizeof(channel_t*)); memset(channel, 0, 5 * sizeof(channel_t*)); for(i = 0; < 5; i++) { channel[i] = open_channel(i); if(channel[i] == null) { fprintf(stderr, "cannot create channel [ %zu ]\n", i); } } /* stuff channels , free them before program exists. however, need loop , pass of them, not 1 */ for(i = 0; < 5; i++) { if (channel[i] != null) /* handle case of opens failed */ { close_channel(channel[i]); } } free(channel);
Comments
Post a Comment