memcpy error checking

have a loaded up system and i am getting invalid pointer when doing a memcpy... it happens very rarely but it is detrimental to the program.

whats the best way to error check (i guess the best way to make sure the pointers are pointing to a accessible piece of memory)

thanks guys!
It's likely your passing a bad pointer to memcpy or overwritting a buffer. This may have happened in a different part of your program and is manifest here.

Start by checking the desination buffer and size and then the source buffer and size.
size should be ok... this is running through a loop that hits it about 20,000 times. and for some reason one spot killed it... i think you might be right about the different part screwing up and manifesting there...

is there a standard way to defend against that? never really had to before
It's an old problem and there is help. What compiler/platform are you using?

If you're using Linux, check out ValGrind.

If you're using Microsoft C++ on Windows, run in debug mode. The debug heap has similar checking to ValGrind.
VS2003 - xp embedded

yeah i tried to use debugger... go through stack to see if what really is causing.. but it only happend once.. and cant get it to go again..

i was just looking for something to put in place to keep me sane knowing that it wont crap out (a quick.. hey if this is no good.. skip and ignore the memcpy)
You can run _heapchk() from time to time to sanity check the heap.
Windows has structured exception handling (SEH) for this

1
2
3
4
5
6
7
8
__try
{
   memcpy(...);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
  // note the failure or just do nothing
}


Best practice is to be fancier in the __except. A more robust solution would pass the exception information to a function that can decide to catch, continue, or look up the stack for a higher exception handler.

This is not C++ and you have to do extra work to get SEH to play well with C++ exceptions.

In the distant past (NT4 era), I saw what may be similar behavior while stress testing some code. In that OS, when you allocated memory, it would only get reserved and it didn't actually get mapped until you used it. This means access violations can occur anywhere. Judicious sprinklings of SEH fixed the issues and made our code stable under stress. I don't know if current Windowses behave the same.
Last edited on
Visual C++ can catch SEH's with the normal C++ syntax, you may have to switch it on. This allows memory violations, floating point errors and the like to be caught in a catch (...) clause.

However, the place where the problem is manifest, may not be the place where problem is caused.
Topic archived. No new replies allowed.