我正在研究一个将在嵌入式ARM GNU/Linux系统上的用户空间中运行的C程序。我需要从char设备节点/ dev/fpga_sram中读取数据。在C程序中,使用malloc分配了一个缓冲区,如下所示。使用read()以char指针读取缓冲区指针
uint16_t *buff;
uint32_t num = 4194304 * 3;
buff = (uint16_t *)malloc(num * sizeof(uint16_t));
使用read()函数,我想数据读入缓冲器的特定索引,如在下面的代码段证明。
int ret;
int fd;
int ptr_loc;
ptr_loc = 0;
fd = open("/dev/fpga_sram", O_RDONLY);
ret = read(fd, &(buff[ptr_loc]), 4194304 * sizeof(uint16_t));
close(fd);
为什么我想这样做是因为缓冲区需要填充在不同时间的设备节点的/ dev/fpga_sram不同读取的原因。缓冲区大小大于读取的总字节数,因此我预计将ptr_loc分配给另一个索引,如下所示。
ptr_loc = 4194304;
fd = open("/dev/fpga_sram", O_RDONLY);
ret = read(fd, &(buff[ptr_loc]), 4194304 * sizeof(uint16_t));
close(fd);
然而,当我试图存储在缓冲区中存取数据,我收到一个段错误:
printf("i = 0, data = %u\n", buff[0]); // this line of code causes segfault
什么我错在这里做的,是有可能从设备节点读取一个指向缓冲区的指针?我假设从设备节点读取将类似于从GNU/Linux中的文件读取。
你检查了malloc的返回吗?你有8Mb的RAM malloc吗? – 2012-01-15 03:09:44
我强烈建议您始终检查返回值,例如malloc并打开。 – mdec 2012-01-15 03:15:54
你确定你没有'read()'超过缓冲区的末尾;如果'ptr_loc> 1',它看起来就像你。 – Dave 2012-01-15 03:16:53