memcpy()函数的分段错误

时间:2018-08-07 11:33:54

标签: c linux memcpy

我有以下内存基址,其中包含一些256字节的数据:

#define TX_PTR 0x40000008

现在我有以下数组,该数组将存储TX_PTR中的数据。

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

当我尝试通过以下方式将数据从内存基地址转移到数组中时:

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

我遇到了细分错误。 我正在linux中运行此代码。这可能是什么问题?

1 个答案:

答案 0 :(得分:3)

  

我正在zynq板上运行freertos和openamp。

从此评论中,我被认为可以在FPGA的地址空间中实现“ 存储器”,或者FreeRTOS正在运行并已写入该存储器。

如果是这种情况,则要访问物理上位于内存中某个点的数据,您需要使用mmap()

Linux进程不位于物理地址上-MMU会将虚拟内存映射到物理内存。

要访问物理内存,您需要使用mmap()-类似这样:

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

在调用mmap()之后,该内存将在您的进程的虚拟地址空间中位于my_memory中保留的地址处-请勿使用{{1 }}。

还要注意,TX_PTR是一个数组,因此可以不使用tx_arr而作为指针传递。

相关问题