FrogTheFrog
FrogTheFrog

Reputation: 1671

Setting pointer out of it's memory range

I'm writing some code to do bitmap blending and my function has a lot of options for it. I decided to use switch to handle those options, but then I needed to either put switch inside a loop (I read that it affects performance) or to assign loop for each switch case (makes code way too big). I decided to do this using third way (see below):

/* When I need to use static value */

BYTE *pointerToValue = (BYTE*)&blendData.primaryValue;
BYTE **pointerToReference = &pointerToValue;
*pointerToReference = *pointerToReference - 3;

/* When I need srcLine's 4th value (where srcLine is a pointer to BYTE array) */

BYTE **pointerToReference = &srcLine;

while (destY2 < destY1) {
    destLine = destPixelArray + (destBytesPerLine * destY2++) + (destX1 * destInc);
    srcLine = srcPixelArray + (srcBytesPerLine * srcY2++) + (srcX1 * srcInc);
    for (LONG x = destX1; x < destX2; x++, destLine += destInc, srcLine += srcInc) {
        BYTE neededValue = *(*pointerToReference + 3); //not yet implemented
        destLine[0] = srcLine[0];
        destLine[1] = srcLine[1];
        destLine[2] = srcLine[2];
        if (diffInc == BOTH_ARE_32_BIT)
            destLine[3] = srcLine[3];
    }
}

Sometimes I might need to use srcLine[3] or blendData.primaryValue. srcLine[3] can be accessed easily with *(*pointerToReference + 3), however to access blendData.primaryValue I need to reduce pointer by 3 in order to keep the same expression (*(*pointerToReference + 3)).

So here are my questions:

  1. Is it safe to set pointer out of its memory range if later it is going to brought back?
  2. I'm 100% sure that it won't be used when it's out of range, but can I be sure that it won't cause any kind of access violation?
  3. Maybe there is some kind of similar alternative to use one variable to capture a value of srcLine[3] or blendData.primaryValue without if(), like it's done in my code sample?

Upvotes: 0

Views: 102

Answers (1)

donjuedo
donjuedo

Reputation: 2505

Because of #2, no usage, the answer to #1 is yes, it is perfectly safe. Because of #1, then, there is no need for #3. :-)

An access violation could only happen if the pointer were actually used.

Upvotes: 2

Related Questions