gcc 4.4.4 c89
我的channel.h文件中有以下代码
typedef struct channel_tag channel_t;
channel_t* open_channel(size_t channel_id);
void close_channel(channel_t *channel);
在我的channel.c文件中
#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);
}
问题在于我的main.c文件。这里我有一个for循环,它创建5个通道对象并为它们分配内存。但是,如果我想在我的程序中稍后释放它们,我不确定如何能够引用它们。这只是我正在测试的5。但后来可能会达到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;
}
非常感谢任何建议,
答案 0 :(得分:4)
好吧,你在主要部分反复重写同一个频道。如果你想要4个通道,你显然需要4个变量来存储它们,或者一个包含4个项目的数组。
channel_t *channel[4]; for (...) channel[i] = open_channel(i);
哦,for (int i = 0; i < 4; i++)
将产生4个循环,而不是5个。
答案 1 :(得分:1)
在创建通道时将通道存储在数组中。确保您可以在程序结束时判断malloc
是否有效(因此此代码中为memset
)。
channel_t **channel = malloc(5 * sizeof(channel_t*));
memset(channel, 0, 5 * sizeof(channel_t*));
for(i = 0; i < 5; i++) {
channel[i] = open_channel(i);
if(channel[i] == 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 < 5; i++) {
if (channel[i] != NULL) /* Handle case where some of the opens failed */
{
close_channel(channel[i]);
}
}
free(channel);
答案 2 :(得分:1)
int main( void )
{
int i = 0;
channel_t** channels = malloc( 5 * sizeof( channel_t* ));
if ( channels == NULL ) exit( 1 ); // error, etc.
for ( i = 0; i < 5; i++ ) {
channels[i] = open_channel( i );
if ( channels[i] == NULL ) {
fprintf( stderr, "Cannot create channel [ %d ]\n", i );
break;
}
}
// ... work, but only if i == 5
for ( i--; i >= 0; i-- ) {
close_channel( channels[i] );
}
free( channels );
return 0;
}