Skip to content
Advertisement

Troubles with using memcpy with mmap

Trying to copy a file using these functions, everything goes fine until program hits the memcpy function which gives a bus error and terminates the process.

JavaScript

Failed to figure out what is wrong, as “Bus Error” isn’t a descriptive error message and there isn’t any much material on the internet regarding this problem.

Advertisement

Answer

When you create the destination file as a new file, its size is 0 bytes. memcpy crashes because it tries to write data beyond the end of the file.

You can make this work by pre-sizing the destination file to the size of the source file (using ftruncate()) before you mmap() it.

Also, you should pass st.st_size as the second argument to mmap, not st.st_size+1. st.st_size+1 tries to map a range that is larger than the size of the file, which is invalid.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement