Skip to content
Advertisement

Segmentation fault on memcpy() function [closed]

I have the following memory base address which contains some data of 256 bytes:

#define TX_PTR 0x40000008

Now I have the following array which will store the data from TX_PTR.

unsigned int tx_arr[64];
int i = 0;
for (i=0; i<64;i++)
{
   tx_arr[i]=0;
}

When I try to memcpy the data from the memory base address to the array by:

memcpy(&tx_arr, TX_PTR, 2*32*sizeof(int));

I get a segmentation fault. I am running this code in linux. What could be the problem here?

Advertisement

Answer

I am running freertos and openamp on a zynq board.

From this comment, I am led to believe that the “memory” is implemented in the FPGA’s address space, or that FreeRTOS is running and has written to this memory.

If this is the case, then to access data that is physically located at a point in memory, you need to use mmap().

Linux processes do not sit on phyisical addresses – the MMU will map virtual memory to physical memory.

To get access to physical memory, you need to use mmap() – something like this:

#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>

#define TX_ADDR 0x40000008
#define TX_LEN  256

void *my_memory;
int memfd;

memfd = open("/dev/mem", O_RDWR);
if (memfd == -1) {
    perror("open()");
    exit(1);
}

my_memory = mmap(NULL, TX_LEN, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, TX_ADDR);
if (my_memory == NULL) {
    perror("mmap()");
    exit(1);
}

/* use my_memory to access the data */
unsigned int tx_arr[64];
int i;

for (i = 0; i < 64; i++) {
   tx_arr[i] = 0;
}

memcpy(tx_arr, my_memory, sizeof(tx_arr));

After the call to mmap(), the memory will be available in your process’ virtual address space at the address held in my_memory – don’t use TX_PTR.

Note also, that tx_arr is an array, and thus can be passed as a pointer without using &tx_arr.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement