arr = new int(10*sizeof(int));
That creates a single int
, initialized to the value of 10*sizeof(int)
. The loop you wrote right after this statement runs out of bounds and it's cause of segmentation fault.
What you want is the array form of new
:
arr = new int[10]; // note 10 only, new expression knows the size
// of the type it allocates
Note that when you assign the pointer to the new array to the pointer to the old array you lose the handle to it and create a memory leak:
int* arr = new int[10];
int* new_arr = new int[20];
arr = new_arr; // original array at arr has leaked
You need to delete[] arr
before you reassign it. Also, I see no use for the third (pos
) pointer. Not even for arrN
, for that matter. One will do. Create a local pointer inside increment
and assign it to arr
when you're done deallocating the old array.
Finally, what people have been telling you in the comments, unless this is a learning exercise, don't try to reinvent the wheel and use std::vector
instead.