Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memcpy() safety on adjacent memory regions

I recently asked a question on using volatile and was directed to read some very informative articles from Intel and others discussing memory barriers and their uses. After reading these articles I have become quite paranoid though.

I have a 64-bit machine. Is it safe to memcpy into adjacent, non-overlapping regions of memory from multiple threads? For example, say I have a buffer:

char buff[10];

Is it always safe for one thread to memcpy into the first 5 bytes while a second thread copies into the last 5 bytes?

My gut reaction (and some simple tests) indicate that this is completely safe, but I have been unable to find documentation anywhere that can completely convince me.

like image 955
JaredC Avatar asked Jan 14 '11 19:01

JaredC


People also ask

Is memcpy insecure?

There are 13 occurrences of memcpy() function which is an insecure function acc to security tool.

Why is memcpy insecure?

Its drawback comes when the source to be copied contains more bytes than its destination, creating overflows that present attackers with opportunities to remotely execute code in the underlying application.

Can memcpy overlap?

The CRT function memcpy doesn't support overlapping memory. The CRT provides an alternative to memcpy that does support overlapping memory: memmove .

Which is faster memcpy or Memmove?

The memmove function is slower in comparison to memcpy because in memmove extra temporary array is used to copy n characters from the source and after that, it uses to copy the stored characters to the destination memory. The memcpy is useful in forwarding copy but memmove is useful in case of overlapping scenarios.


3 Answers

Safe, yes. Performant, no- in this limited example, at least. Remember that one cache line cannot be in two cores at once. You will force core A to wait while core B writes to the buffer, and then wait while the memory is transferred, and then write to it. Multi-core memory copies should be very large in size to avoid this effect.

like image 154
Puppy Avatar answered Oct 30 '22 23:10

Puppy


Yes, it completely safe, serialization of access to the memory bus is done in hardware.

like image 41
Gene Bushuyev Avatar answered Oct 31 '22 00:10

Gene Bushuyev


As long as each instance of memcpy believes it is writing into only its part of the buffer, it is completely safe. Array allocations of any form in C++ are very low-level; it is a contiguous block of storage allocated at the appropriate size for the program, and the array as an object that exists as anything other than a pointer is simply an illusion. Give memcpy non-overlapping ranges of the array, and it has no way of knowing that they aren't simply two completely separate arrays that just happen to be adjacent to each other. The writes won't interfere.

like image 29
Adam Norberg Avatar answered Oct 31 '22 00:10

Adam Norberg