ptr[j] = ptr[j + 1]; is an out of bounds access if it's only the last element in the array that is negative. the oob access can be avoided by changing the condition in for (int j = i; j < n; j++) to j < n-1