Access violation in pointer arithmetic
With code:
int nsize;
int * buffer;
char TargetBuffer[4096];
const SIZE_T buffersize = (320*240) * sizeof(int);
buffer = (int *) malloc(bufferSize);
// fill buffer with data
nsize = 0;
while(nsize < buffersize)
{
// HERE after some loops i get Access Violation
memcpy(TargetBuffer, buffer + nsize, 4096);
// do stuff with TargetBuffer
nsize += 4096;
}
Why am I getting an access violation? What should I change?
When you add buffer + nsize
, you have to understand what you are actually adding buffer + (nsize * (sizeof(int))
, as it int *
is when you do pointer arithmetic.
So it probably has something to do with it. Try increasing nsize by nsize += 4096/sizeof(int)
or something smarter.
I would do something like this:
SIZE_T left = buffersize;
nsize = 0;
while(left)
{
SIZE_T block = (left >= 4096)?4096:left;
// HERE after some loops i get Access Violation
memcpy(TargetBuffer, buffer, block);
buffer += (left) / sizeof(*buffer);
// do stuff with TargetBuffer
left -= block;
}
I'm sure the problem you are seeing is that you are going over the edge because your code doesn't care about dimensions that are not multiples of 4K.
Update the loop while
as
while(nsize < (buffersize/sizeof(int))
buffer
for int
, not char
. int
takes multiple bytes, you re-read and copy from memory that is not part buffer
.