構造体の構成によっては、メモリの割り当てや割り当て解除を処理する関数を実際に作成したり、構造バッファーを処理するための不透明なデータ型として使用できるハンドルを与えることができます。たとえば、構造体に他のメモリバッファへのポインタが含まれている場合、構造体のバッファにはmalloc
とfree
の呼び出しを単に組み合わせることはできません。配列全体をループし、構造体内のポインタを解放する必要があります最初に構造体を解放する前に、構造体内のポインタデータメンバのメモリリークを作成します。
だから、例えば、あなたが次のことを行うことができます:
typedef struct audio_struct
{
int array_size;
unsigned char* buffer;
} audio_struct;
typedef audio_struct* audio_handle;
//this returns an allocated pointer to the caller.
//caller takes ownership of the pointer.
audio_handle alloc_audio_func(int buffer_size)
{
audio_handle temp;
temp = malloc(sizeof(audio_struct) * buffer_size);
return temp;
}
void fill_audio_arrays(audio_handle handle, int buffer_size)
{
for (int i=0; i < buffer_size; i++)
{
handle->buffer = malloc(SOME_SIZE);
handle->array_size = SOME_SIZE;
}
return;
}
//frees the buffer pointed to by the handle (i.e., pointer), and any associted
//dynamic memory being pointed to by each structure's pointer-member
//handle is invalid after function call (i.e., points to deallocated memory)
void dealloc_audio_buffer(audio_handle handle, int buffer_size)
{
for (int i=0; i < buffer_size; i++)
{
free(handle->buffer);
}
free(handle);
return;
}
あなたはそれらの構造自体が追加含まれている場合は特に、常にforループ、あなたのバッファの構造要素を処理するために書く必要はありません。この方法であなたが処理しなければならない動的に割り当てられたメモリへのポインタ。
ガベージコレクタがないので、Cとあまり関係ありません。もしあなたがヒープ(mallocなど)に何かを割り当てるならば、それを済ませたら 'free'する必要があります。 – GWW
参照:http://stackoverflow.com/questions/5556125/using-functions-in-c-return-value – ninjalj
最も簡単なのは、割り当てにポインタ(および 'malloc')を使用するのではなく、それらをローカル変数として割り当てることですスタック上にある。 –