我正在尝试用 C 语言编写程序来进行垂直冗余检查。代码如下:
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
int main()
{
int fd,i;
char *data = "01010101010111110101010101011111";
int count = 0,bit_count=0;
char *parity_bit_array = NULL;
char *data_to_send = NULL;
char *stream_name = "Named Stream";
do
{
if(*data == '1' && bit_count <= 8)
{
count++;
if(bit_count == 8)
{
if( count % 2 == 0)
{
*parity_bit_array = '1';
count = 0;
bit_count = 0;
}
else
{
*parity_bit_array = '0';
count = 0;
bit_count = 0;
}
}
}
bit_count++;
data++;
} while( !data);
do
{
if(bit_count <= 8)
{
*data_to_send++ = *parity_bit_array++;
}
*data_to_send++ = *data;
} while( !data );
printf("%s \n",data_to_send);
mkfifo(stream_name,0666);
fd = open(stream_name,O_WRONLY);
write(fd,data_to_send,sizeof(data_to_send));
close(fd);
unlink(stream_name);
return 0;
}
下面所示的文件是发送方文件,接收方要读取其中的数据。 通过使用大小数组,它可以正常工作,但我喜欢将它与指针一起使用。 此代码中的主要变量:
- 数据:要实现 VRC 的数据
- 计数:偶校验位计数为 1
- bit_count:计算 8 位
- parity_bit_array:收集数据中每个字节的奇偶校验位
- data_to_send:data + parity_bit_array 的组合
例如: 数据: 01110000 parity_bit_array:1 要发送的数据: 011100001
最佳答案
您没有为 char 指针分配内存,并且您正在尝试写入它们,这将导致未定义的行为,从而导致段错误。
*parity_bit_array = '1';
这段代码中有多个这样的情况。
char *data_to_send = NULL;
data_to_send 指针从未分配内存,并且您尝试写入它
*data_to_send++ = *parity_bit_array++;
为 char 指针分配内存,例如
char *data_to_send = malloc(20);
在写入此数组时,如果您看到已写入 20 个字节,只需对同一内存执行 realloc()
char *temp = realloc(data_to_send,40);
if(temp != NULL)
data_to_send = temp;
关于c - 垂直冗余检查中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28831520/