title: C - Memory access with mmap
body: <p>I have a hex file of 327680 characters which I'm writing to physical address 0x30000000 - 0x3004FFFF on the memory on my ARM linux system.  </p>
  
  <p>While reading back from the memory I'm getting a segfault after reading 64170 characters from the start address, ie at 0x3000FAAA. 
  If I change my starting address to 0x3000FA64, then also I get a segfault after 64170 characters. </p>
  
  <p>How do I ensure data is accessed correctly if Data > 4kB (page size) ?</p>
  
  <p>I'm unable to understand the exact problem, so I'm adding the snippet of my code below:</p>
  
  <pre><code>#define MAX_RANGE 327679
  
  int fd;
  FILE* fd_table=NULL;
  unsigned long int count = 0 ;
  void * mem;
  void * aligned_vaddr;
  unsigned long aligned_paddr;
  uint32_t aligned_size;
  unsigned long int addr_phys;
  
  uint8_t *addr;
  int g_size = 1;
  unsigned long int g_paddr = 0x30000000; //Starting physical address
  
  while((count&lt;MAX_RANGE)){
    g_paddr = addr_phys;
    g_paddr &amp;= ~(g_size - 1);
  
    aligned_paddr = g_paddr &amp; ~(4096 - 1);
    aligned_size = g_paddr - aligned_paddr + (g_count * g_size);
    aligned_size = (aligned_size + 4096 - 1) &amp; ~(4096 - 1);
  
    /* Align address to access size */
    aligned_vaddr = mmap(NULL, aligned_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, aligned_paddr);
    if (aligned_vaddr == NULL) {
      printf("Error mapping address\n");
      close(fd);
      return 1;
    }
  
    mem = (void *)((uint32_t)aligned_vaddr + (g_paddr - aligned_paddr));
    addr = mem;
    fprintf(fd_table, "%02X\n",addr[0]);
    addr_phys +=1; //Increment byte address
    count++;
  }
  </code></pre>
  
  <p>Note: 
  1. There is no error in the write process, I have verified by viewing the segfault address with memtool.
  2. The address 0x30000000 onwards is not used by the system (I have ensured that in the u-boot). </p>