memcpy() 函数的分段错误
Segmentation fault on memcpy() function
我有以下内存基地址,其中包含一些 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 到数组时:
memcpy(&tx_arr, TX_PTR, 2*32*sizeof(int));
我遇到了分段错误。
我是运行这个代码在linux。这可能是什么问题?
I am running freertos and openamp on a zynq board.
根据这个评论,我相信“memory”是在 FPGA 的地址 space 中实现的,或者 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()
后,内存将在您进程的 虚拟地址 space 中可用,地址为 my_memory
] - 不要使用 TX_PTR
.
另请注意,tx_arr
是一个数组,因此可以在不使用 &tx_arr
的情况下作为指针传递。
我有以下内存基地址,其中包含一些 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 到数组时:
memcpy(&tx_arr, TX_PTR, 2*32*sizeof(int));
我遇到了分段错误。 我是运行这个代码在linux。这可能是什么问题?
I am running freertos and openamp on a zynq board.
根据这个评论,我相信“memory”是在 FPGA 的地址 space 中实现的,或者 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()
后,内存将在您进程的 虚拟地址 space 中可用,地址为 my_memory
] - 不要使用 TX_PTR
.
另请注意,tx_arr
是一个数组,因此可以在不使用 &tx_arr
的情况下作为指针传递。