From the course: Secure Coding in C

Unlock this course with a free trial

Join today to access over 25,600 courses taught by industry experts.

Performing pointer math

Performing pointer math - C Tutorial

From the course: Secure Coding in C

Performing pointer math

- [Instructor] In this code, storage is allocated for 10 integer values. Pointer a references integer-size chunks in memory. It's used to fill the buffer with integer values. In the for loop, pointer a increments for each iteration. As it does, it holds the address of the next integer within the buffer. The problem here is that the original address is lost. Where does the buffer start? In fact, this statement causes the program to crash because variable a no longer references the allocated block. In this exercise file, pointer math is used to reset the address of pointer a. So after the buffer is filled, this statement points a back to the start of the buffer. The effect is, once again, a points to the buffer's base, and because an offset is used here, the base isn't lost when it's free. Here's the output. But this code is still flawed. You may not always know where a pointer is relative to its original value. Specifically, if the pointer you're manipulating is the only reference to…

Contents