1

我正在尝试使用以下结构实现环形缓冲区

/*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;
   }

我在 main 中调用这个函数:

 struct rb *newRB = (struct rb*)create(100);

但是,我在为结构分配内存的步骤中遇到了问题。在调试模式下,我可以看到 head、tail、count 的值被分配了非常奇怪的大数字,但不是 0。在第一步之后程序挂起,没有给我任何异常。

有人可以帮我解释一下这个问题吗?我该如何解决?

4

3 回答 3

3

我很难阅读您的代码,但根据我的收集,您可能想要执行以下操作:

struct rb *create(int n)
{
    struct rb newRb = calloc(1, sizeof(struct rb));
    newRb->rbArray = calloc(n, sizeof(char*));

    newRb->count = n;

    return newRb;
}

calloc 将确保分配空间的内容设置为零。此外,仅n*sizeof(char*)在您第一次调用 malloc 时分配一个附加值似乎很可疑。

于 2010-09-15T07:45:15.910 回答
0

以下应该是执行相同操作的更短方法:

struct rb *create(int n)
{
    struct rb * newRb = calloc(sizeof(struct rb) + n*sizeof(char*), 1);
    newRb->size = n;    
    return newRb;
}

这会将所有分配的空间设置为0,然后size正确设置该字段。

于 2010-09-15T12:07:28.323 回答
0

非常感谢你们的帮助。我使它与 char** 一起工作,它绝对比灵活地工作数组成员容易得多。

但是,我想知道,当你有 char **array; 你可以使用array[i],它会给你一个指向char的指针。为什么如果我们有 char *array; 我们不能使用 array[i] 来获取字符吗?

希望我在这里足够清楚。

谢谢

于 2010-09-15T15:23:33.927 回答