Skip to content

Chapter 12 Exercise 12 - pointer increments to point outside the array #127

@ShaunakRawat

Description

@ShaunakRawat

The suggested solution can store an erroneous value in largest or cause undefined behaviour.

Problem:
Incrementing p right after checking p < a+n causes a problem after p is incremented to point to the last element in the array: a+(n-1). After the iteration completes, the condition is checked and because a+(n-1) < a+n is true, the loop proceeds to increment p to point to a + n (out of bounds of the array) and continue the loop, potentially causing undefined behaviour.

Suggested solution:
Change p++ to ++p.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions