C语言 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 中运行此代码。这里可能有什么问题?

我在zynq板上运行freerto和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 中 - 不要使用 TX_PTR

另请注意,tx_arr是一个数组,因此可以在不使用 &tx_arr 的情况下作为指针传递。

最新更新