次の構造体でリングバッファを実装しようとしています
/*head, tail are indexes of the head and tail of ring buffer
*count is the number of elements; size is the max size of buffer
*rbArray is an array to pointer of char used to store strings
*/
struct rb{
int head;
int tail;
int count;
int size;
char *rbArray[];
};
次に、次の関数を使用して文字列バッファーを作成します。
struct rb *create(int n){
/*allocate memory for struct*/
struct rb *newRb = (struct rb*)malloc(sizeof(struct rb)+ n*sizeof(char *));
assert(newRb);
int i;
for(i=0;i<n;i++)
newRb->rbArray[i] = NULL;
/*put head and tail at the beginning of array
initialize count, set max number of elements*/
newRb->head = 0;
newRb->tail = 0;
newRb->count = 0;
newRb->size = n;
return newRb;
}
私はこの関数をメインで呼び出します:
struct rb *newRB = (struct rb*)create(100);
しかし、構造体にメモリを割り当てるステップで問題が発生します。デバッグモードでは、head、tail、countの値に非常に奇妙な大きな数値が割り当てられていますが、0は割り当てられていません。この最初のステップの後、プログラムは例外をスローせずにハングします。
誰かが私にこの問題を説明するのを手伝ってもらえますか?どうすれば修正できますか?