Nicholas Kinar
Nicholas Kinar

Reputation: 1470

Reading from char device using read() with pointer to buffer

I am working on a C program that will run in user space on an embedded ARM GNU/Linux system. I need to read data from a char device node /dev/fpga_sram. Within the C program, a buffer has been allocated using malloc, as shown below.

uint16_t *buff;
uint32_t num = 4194304 * 3;
buff = (uint16_t *)malloc(num * sizeof(uint16_t));

Using the read() function, I would like to read data into a certain index of the buffer, as demonstrated in the code snippet below.

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);

The reason why I want to do this is because the buffer needs to be filled with different reads from the device node /dev/fpga_sram at different times. The buffer size is greater than the total number of bytes read, so I would anticipate assigning ptr_loc to another index, as demonstrated below.

ptr_loc = 4194304;    
fd = open("/dev/fpga_sram", O_RDONLY);
ret = read(fd, &(buff[ptr_loc]), 4194304 * sizeof(uint16_t));
close(fd);  

However, when I try to access data stored in the buffer, I receive a segfault:

printf("i = 0, data = %u\n", buff[0]);   // this line of code causes segfault

What am I doing wrong here, and is it possible to read from the device node with a pointer to a buffer location? I would assume that reading from the device node would be similar to reading from a file in GNU/Linux.

Upvotes: 3

Views: 4446

Answers (1)

Kyle Jones
Kyle Jones

Reputation: 5532

Ignoring the reading business, the only reason for the printf to produce a SEGV is that buff points someplace outside the process's valid memory. So use printf("%p", buff) and find out where buff is pointing, and sprinkle these in your code until you find out when it stops pointing to the address that malloc returned.

Upvotes: 4

Related Questions