The first time this is hit, counter1 and 2 are both negative values. This is undefined behavior. You're likely writing into memory that isn't yours, or some compilers treat this as indexing from the back going to the front. Why not initialize the counters to 0?