Search code examples
c++linuxvirtualmmap

mmap gets corrupted, is malloc overriding elements on memory


I've been having random problems in the data files, those data files are accessed for read only using mmap (they are big), and I've been trying to locate the source of the error, what I noticed is that the files get corrupted at the end with random data from whatever is executing at that moment, (extracts from the console, some logs that are been executed by other programs, etc.). Today, my program crashed again, but this time I noticed that the corrupted file is only open as read-only, which does not make sense. How is that a file gets corrupted if it was open using this:

FILE _pFile = ::open(fileName, O_RDONLY);
char* _addr = reinterpret_cast<char *>(mmap(NULL, fileLenRequired, PROT_READ, MAP_FILE | (shared?MAP_SHARED:MAP_PRIVATE) | MAP_POPULATE , _pFile, offset));

Reading some other questions makes me think that mmap is not "protected" and it might be overridden/overlapped by malloc calls, how do I prevent this?

By the way, I thought this was caused by a memory leak, or a wrong pointer, therefore I did a full check using valgrind and fixed several problems, but the files keep corrupting from time to time.


Solution

  • Ok, Finally I discovered what was wrong with this, the problem was not the mapped files, Originally I thought the system was crashing because the files somehow got corrupted, what I found is that the crash happened first and then any opened file gets corrupted with trash. The problem is that it was really hard to reproduce and only occurred in a production server, I'd to crack my head to figure out what was wrong with this.

    Thanks to everyone for taking the time to read and try to suggest options, at least this served to check if I was not doing something clearly wrong in my code.