Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22458

Why does unaligned access to mmap'ed memory sometimes segfault on AMD64?

$
0
0

I have this piece of code which segfaults when run on Ubuntu 14.04 on an AMD64 compatible CPU:

#include <inttypes.h>#include <stdlib.h>#include <sys/mman.h>int main(){  uint32_t sum = 0;  uint8_t *buffer = mmap(NULL, 1<<18, PROT_READ,                         MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);  uint16_t *p = (buffer + 1);  int i;  for (i=0;i<14;++i) {    //printf("%d\n", i);    sum += p[i];  }  return sum;}

This only segfaults if the memory is allocated using mmap. If I use malloc, a buffer on the stack, or a global variable it does not segfault.

If I decrease the number of iterations of the loop to anything less than 14 it no longer segfaults. And if I print the array index from within the loop it also no longer segfaults.

Why does unaligned memory access segfault on a CPU that is able to access unaligned addresses, and why only under such specific circumstances?


Viewing all articles
Browse latest Browse all 22458

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>