Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can incrementing a pointer without dereferencing still segfault or have other (un)defined nastiness?

All of the examples I've been able to find online about incrementing a pointer causing a segfault involved the dereference of the pointer - what if I just want to increment it (for example at the end of a for loop) and I don't care if it ends up in invalid memory because I won't use it again. For example, in this program I just need to step by 4 every iteration, but I never dereference these pointers again after the last iteration.

float* leftRowPointer, resultRowPointer;
// assume they were correctly initialized

for (unsigned int i = 0; i < 4; ++i, leftRowPointer += 4, resultRowPointer += 4) {
    // do some stuff
}

Do I need to do something like this instead?

for (unsigned int i = 0; i < 4; ++i) {
    // same stuff
    if (i != 3) {
        leftRowPointer += 4;
        resultRowPointer += 4;
    }
}

Is there a better way to accomplish what I'm trying to do?

When I've tried it myself nothing bad seems to happen, but that's hardly a guarantee that it will always work, and unfortunately I don't have access to Valgrind or similar at work.

We're using the C++11 standard, fwiw, and I couldn't find anything in there that directly applies to this, but I'll be the first to admit that I don't know the standard well enough to have a good idea of where to look for it.

like image 406
Dan Oberlam Avatar asked Jan 08 '16 15:01

Dan Oberlam


People also ask

What can cause Segfault?

In practice, segfaults are almost always due to trying to read or write a non-existent array element, not properly defining a pointer before using it, or (in C programs) accidentally using a variable's value as an address (see the scanf example below).

Does dereferencing a null pointer cause a segmentation fault?

If the program dereferences the null pointer, it can cause a segmentation fault or other undefined behavior, which can lead to a crash.

What is the segmentation fault error in C?

A segmentation fault occurs when your program attempts to access an area of memory that it is not allowed to access. In other words, when your program tries to access memory that is beyond the limits that the operating system allocated for your program.


1 Answers

Section 5.7, "Additive operators", paragraph 5 specifies this - the result of the addition itself is undefined; the program isn't valid even if you never dereference the pointers.

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

It's highly unlikely to segfault even though it's allowed to, but it's still undefined with all that entails.

like image 60
molbdnilo Avatar answered Sep 30 '22 16:09

molbdnilo