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.
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).
If the program dereferences the null pointer, it can cause a segmentation fault or other undefined behavior, which can lead to a crash.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With