Can a pointer increment without playing another segfault or have another (un) specific muck?

All the examples that I could find on the Internet about increasing the pointer that causes segfault are related to dereferencing the pointer - what if I just want to increase it (for example, at the end of the for loop) and it doesn't matter if it gets into the wrong memory because I will not use it again. For example, in this program, I just need to perform step 4 at each iteration, but I never play 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?

 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 tried it myself, nothing bad happens, but this hardly guarantees that it will always work, and, unfortunately, I do not have access to Valgrind or the like at work.

We use the C ++ 11 standard, fwiw, and I could not find anything there that directly relates to this, but I will be the first to admit that I do not know the standard well enough to have a good idea of ​​where it is to search.

+8
c ++ memory-management undefined-behavior pointers segmentation-fault
source share
2 answers

Section 5.7 “Additive operators”, paragraph 5, indicates this: the result of the addition itself is undefined; the program is invalid even if you never play pointers.

If both pointer operands and the result point to elements of the same array object or one after the last element of the array object, the evaluation should not lead to overflow; otherwise, the behavior is undefined.

This is very unlikely for segfault, although it is allowed, but it is still undefined with everything that entails.

+8
source share

Just assigning the wrong pointer reference would cause a problem, initializing one to NULL also be a problem. Therefore, the answer to your specific question is no.

+4
source share

All Articles