Reputation: 1179
With the 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 get the Access Violation? What should I change?
Upvotes: 3
Views: 165
Reputation: 129504
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 pretty sure the problem you see is that you are going over the edge because your code isn't taking care of sizes that are not multiples of the 4K.
Upvotes: 3
Reputation: 53386
Update your while
loop as
while(nsize < (buffersize/sizeof(int))
buffer
is for int
s and not char
. int
takes multiple bytes, you are over counting and copying from memory which is not part of buffer
.
Upvotes: 0
Reputation: 181430
When you add buffer + nsize
you have to realize that you are actually adding buffer + (nsize * (sizeof(int))
since it's a int *
when you are doing pointer arithmetic.
So it probably has something to do with it. Try incrementing nsize by nsize += 4096/sizeof(int)
or something more clever.
Upvotes: 9