Thread: Misaligned memory access

  1. #1
    The C-er
    Join Date
    Mar 2004
    Posts
    192

    Lightbulb Misaligned memory access

    Hi all,

    Do any of you guys have experience of using misaligned memory accesses for any reason?

    Usually, it's something you want to avoid, because it's both a non-portable behaviour, and is slower than an aligned access.
    However my current project has compelling reasons to do so. (It's an engine for running Conways "game of life" if you're interested).

    For instance this simple fragment:
    Code:
    int foo[100];
    int word = 3;
    int offset = 1;
    int *misaligned = (int*)((char*)&foo[word] +offset);
    *misaligned += 0x12345678;
    This takes array foo, and updates bytes 13 - 16 within it.

    I made foo an array of ints here, because it's accessed that way elsewhere. This isn't a totally fictitious example, I actually do something like this in my code.

    Is there a neater way to do this? All those casts look untidy!

  2. #2
    Registered User
    Join Date
    Jun 2004
    Posts
    722
    Untidy?? Don't worry, they're pretty readble, and when working with memory adresses that's what you have to do. But...
    maybe this is cleaner??
    Code:
    int foo[100];
    int word = 3;
    int offset = 1;
    char *ptr = (char*)foo;
    //use sizeof(int) instead 4 if your concearning portability
    int *misaligned = (int*)(ptr+word*4+offset);
    *misaligned += 0x12345678;

  3. #3
    The C-er
    Join Date
    Mar 2004
    Posts
    192
    Thanks for that vote of confidence xErath.

    I like your way too (seems a bit purer somehow) but I like to have the array index explicit in the code (in reality it's a 2D array)

    FYI, the core of this program originated on 68000 processor, but written in assembly language. I decided to dust it off + create a win86 version on the same principle.

    Doing weird pointer mangling is easy in 68k, but I have to work around C to do it here it seems.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 09-04-2008, 01:27 PM
  2. Direct memory access?
    By _izua_ in forum Windows Programming
    Replies: 4
    Last Post: 08-01-2008, 02:08 AM
  3. Question regarding Memory Leak
    By clegs in forum C++ Programming
    Replies: 29
    Last Post: 12-07-2007, 01:57 AM
  4. Onboard video card memory access
    By HermioneFan in forum Game Programming
    Replies: 1
    Last Post: 05-28-2003, 09:53 AM
  5. Memory Access Error when using Strcpy()
    By fgs3124 in forum C Programming
    Replies: 2
    Last Post: 03-15-2002, 03:07 PM