Misaligned Pointer Performance
        Posted  
        
            by Elite Mx
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Elite Mx
        
        
        
        Published on 2010-06-16T21:53:11Z
        Indexed on 
            2010/06/16
            22:02 UTC
        
        
        Read the original article
        Hit count: 177
        
Aren't misaligned pointers (in the BEST possible case) supposed to slow down performance and in the worst case crash your program (assuming the compiler was nice enough to compile your invalid c program).
Well, the following code doesn't seem to have any performance differences between the aligned and misaligned versions. Why is that?
/* brutality.c */
#ifdef BRUTALITY
    xs = (unsigned long *) ((unsigned char *) xs + 1);
#endif
...
/* main.c */
#include <stdio.h>
#include <stdlib.h>
#define size_t_max ((size_t)-1)
#define max_count(var) (size_t_max / (sizeof var))
int main(int argc, char *argv[]) {
    unsigned long sum, *xs, *itr, *xs_end;
    size_t element_count = max_count(*xs) >> 4;
    xs = malloc(element_count * (sizeof *xs));
    if(!xs) exit(1);
    xs_end = xs + element_count - 1; sum = 0;
    for(itr = xs; itr < xs_end; itr++)
        *itr = 0;
#include "brutality.c"
    itr = xs;
    while(itr < xs_end)
        sum += *itr++;
    printf("%lu\n", sum);
    /* we could free the malloc-ed memory here */
    /* but we are almost done                  */
    exit(0);
}
Compiled and tested on two separate machines using
gcc -pedantic -Wall -O0 -std=c99 main.c
for i in {0..9}; do time ./a.out; done
© Stack Overflow or respective owner