C 用普通内存分配替换/dev/mem映射时8位内存访问的行为

C 用普通内存分配替换/dev/mem映射时8位内存访问的行为,c,memory,C,Memory,所以,我观察了不同位字的执行时间,下面是一个读取8位字的程序示例。我想检查当我们用“正常”内存分配(即malloc/calloc)替换/dev/mem映射时它的行为。但我的代码开始出现分段错误(核心转储)。有什么帮助吗 #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include &

所以,我观察了不同位字的执行时间,下面是一个读取8位字的程序示例。我想检查当我们用“正常”内存分配(即malloc/calloc)替换/dev/mem映射时它的行为。但我的代码开始出现分段错误(核心转储)。有什么帮助吗

#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>

static uint32_t map_size = 0x08000000;
static uint32_t map_base = 0x18000000;
static uint32_t map_addr = 0x00000000;
static uint64_t cycle_count = 0x1000000;


static char *dev_mem = "/dev/mem";

int main(int argc, char **argv) {
int fd;
uint8_t *buf;
if ((fd = open(dev_mem, O_RDWR | O_SYNC)) == -1) {
    printf("can't open /dev/mem .\n");
    exit(EXIT_FAILURE);
}

buf = (uint8_t *) malloc(sizeof(uint8_t));
if (buf == 0) {
    printf("Can't be mapped. \n");
    exit(EXIT_FAILURE);
} else
    map_addr = (long unsigned) buf;

uint8_t sum = 0;

while (cycle_count-- > 0)
    sum += *buf++;

printf("%u\n", sum);
close(fd);
exit(EXIT_SUCCESS);


return 0;
  }
#包括
#包括
#包括
#包括
#包括
#包括
#包括
静态uint32映射大小=0x08000000;
静态uint32\u t映射\u基=0x18000000;
静态uint32映射地址=0x00000000;
静态uint64\u t循环计数=0x1000000;
静态字符*dev_mem=“/dev/mem”;
int main(int argc,字符**argv){
int-fd;
uint8_t*buf;
如果((fd=打开(dev_mem,O_RDWR | O_SYNC))=-1){
printf(“无法打开/dev/mem。\n”);
退出(退出失败);
}
buf=(uint8_t*)malloc(sizeof(uint8_t));
如果(buf==0){
printf(“无法映射。\n”);
退出(退出失败);
}否则
map_addr=(长无符号)buf;
uint8_t sum=0;
而(循环计数-->0)
总和+=*buf++;
printf(“%u\n”,总和);
关闭(fd);
退出(退出成功);
返回0;
}
我是新手,如果这些错误很愚蠢,我很抱歉。

看看这个:

总和+=*buf++

将buf指向的值添加到sum中,然后递增buf。所以实际上是增加地址,而不是增加值。 只需添加一个括号即可解决问题:

 sum += (*buf)++;

您应该阅读更多有关后缀增量运算符和的信息。

您是否尝试读取相同的单词循环计数次数?是的,我认为这不是问题所在,是吗?