圆形字符阵列缓冲区 - c

时间:2016-04-23 01:44:53

标签: c arrays multithreading circular-buffer

我正在使用char *数组来创建缓冲区,以将信息从多个映射线程移动到缩减线程。我需要使数组循环,但是,当阵列用完房间时,我不断收到分段错误。如何使阵列圆形?我目前有

for(j = 0; j < i; j++){
    int next = mr->nextIndex + j;
    if(next > 1023){
        next = 0;
    }
    mr->buffer[next] = temp[j];
}

数组设置为,

new_mr->buffer = malloc(sizeof(char *) * MR_BUFFER_SIZE);

宏为1024.感谢任何帮助。

temp是

char *temp = malloc(sizeof(char *));

并从

获取其价值
memcpy(temp, kv, i);

和kv从main传递给函数。

2 个答案:

答案 0 :(得分:0)

这是错误的:

char *temp = malloc(sizeof(char *));

您使用memcpy()将一些数据存储到那里,但存储空间仅为sizeof(char*),即4或8个字节。您可能打算在那里使用其他尺寸,例如您传递给i的{​​{1}}的值。

答案 1 :(得分:0)

char *temp = malloc(sizeof (char *));

应该是

char *temp = malloc(sizeof (char) * i); // sizeof (char) can be omitted

因为temp应指向char的数组。

mr->buffer[next] = temp[j];

应该是

mr->buffer[next] = &temp[j];

因为mr->buffer[next]的类型为char *

相关问题