-2

I'm writing a class member function to remove a row from a (m x n) matrix. The memory model for the matrix (from a standard linear algebra library) is guaranteed to be a contiguous block such that the (i, j)th element maps to the (i * n + j)th element of that memory block.

I'd like to use ::memcpy for clarity and performance reasons. (The alternative ways using for loops are cumbersome.) But I need some reassurance.

In general, the destination location overlaps the source location since, if I'm deleting row r, I'd use (dropping any casts for clarity),

::memcpy(r * n, (r + 1) * n, bigger than n in general)

If ::memcpy is guaranteed to copy from the start of the block, then this will be fine. But, does the standard guarantee this? I can't see why it would and suspect the behaviour of such code is undefined.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 6
    http://stackoverflow.com/questions/4415910/memcpy-vs-memmove – thang Mar 12 '14 at 09:38
  • On modern systems, a `for` loop will frequently perform as well or better than `memcpy`. Some compilers can take advantage of type and alignment information when you invoke through a `for` loop but not when you call `memcpy`. (And *way* better than `memmove` since the direction is more likely to be determined at compile time rather than at run time.) – David Schwartz Mar 12 '14 at 10:03

2 Answers2

2

You should use memmove instead of memcpy. The overlapping behaviour for memmove is defined.

User thang pointed out in a comment, there is a related article which dicusses the difference between memcpy and memmove.

Community
  • 1
  • 1
Flovdis
  • 2,945
  • 26
  • 49
1

Have you considered using std::copy or std::copy_backwards?

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157