c++ array iteration with addresses
I am new to c++ and trying out some stuff. So recently I tried to create an int array on the heap and iterate it with addressation instead the standard way with [x].
Everytime I execute my code I get a heap corruption error. I tried several things (also searched here on stackoverflow) but could not find any answers.
int* p = new int[5];
for (int i = 0; i <= 4; i++){
/*p[i] = i;
cout << p[i] << endl;*/ //This is the standard way and works
*p = i;
cout << *p << endl;
p = (p + sizeof(*p)); //iterate the pointer through the heap addresses
}
delete[] p;
The application runs and shows me the filled array values {0,1,2,3,4} but then crashes.
I get following error message:
HEAP CORRUPTION DETECTED: after CRT Block (#225) at 0x00C31B68. CRT detected that application wrote to memory after end of heap buffer...
Thanks in advance
In pointer arithmetics an expression p + i
, where p
is a pointer to an array's element and i
is integer, is equivalent to &(p[i])
, that is a pointer to the array's element i
positions after the one pointed at by p
.
That's why stepping to the next element is performed by p = p+1
(or equvalently p += 1
or simply ++p
).
Note however the incrementation does no checking for the array bounds – you're able to safely access the next item(s) provided they belong to the same array. If you step beyond the last item of an array you may get memory access error or just read some garbage.
See for example
http://www.tutorialspoint.com/cplusplus/cpp_pointer_arithmatic.htm
https://www.eskimo.com/~scs/cclass/notes/sx10b.html
When you do this
p = (p + sizeof(*p));
you are taking sizeof(int)
int-sized steps across the array, going beyond its bounds.
You need to take single steps:
p = (p + 1);
or
++p;
But note that after doing that, p
no longer points to any place you can call delete[]
on. You need to keep a pointer to the original address:
int* arr = new int[5];
int* p = arr;
....
delete[] arr;
But you have no reason to allocate the array with new
in the first place.
int arr[5];
int * p = arr;
....
p = (p + sizeof(*p));
results in a jump of 4
with every iteration, as sizeof(int)
is equal to 4
. Hence, you are going out of bounds.
The standard way, that is :
p[i] = i;
cout << p[i] << endl;
is correct, as i
increases by 1
in every iteration.
上一篇: HEAP CORRUPTION DETECTED:after Normal block
下一篇: 带地址的c ++数组迭代