1

I would like to create a sub array which is offset from the original array without copying the contents.

i.e

byte* arr = new byte[4];
//0...3 meaning 0 through 3
arr[0...3] = 1...4

byte* subarr = arr+2;

So that subarr[0] is equal to 3. This actually does work; if I print subarr[0] I get 3. However if I want to use it in a function such as memcpy(), I get an error:

There isn't actually an error message, but the breakpoint is in free_base.cpp. The breakpoint in my code is at memcpy. The actual use case is:

byte* tempbuffer = new byte[size+2];
ReadProcessMemory(processHandle, (PBYTE*)(moduleStart + offset - 1), tempbuffer, size+2, 0);

byte* subbuffer = tempbuffer + 1;
assert(subbuffer[0] == tempbuffer[1]);
memcpy(out_buffer, subbuffer, size);

delete[] subbuffer;
delete[] tempbuffer;

I know the sub array in this example is redundant because I can literally just pass the buffer into ReadProcessMemory however this was just to find the bug. If I pass out_buffer (which is an LPVOID) directly to ReadProcessMemory I get valid results and no errors. Also if I use memcpy on tempbuffer (the original array), it also gives me what I want with no errors. So the error must be caused by the sub array and using memcpy on it.

Why is this happening and what can I do as an alternative?

Thanks.

9
  • 1
    There is no such thing as a sub-array. You are performing basic pointer arithmetic. What is your question, actually? Commented Apr 24, 2016 at 16:31
  • 3
    I think the error comes from delete[] subbuffer; You shouldn't destroy anything not comming directly from new. Commented Apr 24, 2016 at 16:35
  • 1
    gdlmx is probably right. Still, if you have a question about an error, you need to present your minimal reproducible example before we move to answer it. As it stands, you didn't even tell us what the error you're asking about is. Commented Apr 24, 2016 at 16:35
  • 1
    memcpy doesn't know anything about overlapping blocks, for your purposes it is safety to use memmove. Commented Apr 24, 2016 at 16:48
  • 1
    Seems that you're using a debugger, is it a way to catch the exception and display some useful message? It is very hard to spot the problem without knowing what kind of exception you got. Commented Apr 24, 2016 at 16:51

1 Answer 1

1

Your code regarding the sub buffer is fine, the reason there is an error occuring in your debugger is because you're calling delete[] on subbuffer. You should not be doing that, you only need to delete[] on tempbuffer because that's the only var that was created with new. I tested your code and verified this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.