CopyMemory gives segmentation fault

My program is supposed to take input via the console and use shared memory so that another process can get access to the input. Apparently CopyMemory is causing a segmentation fault.

    std::string Input;
    std::cout << "What Text do you want to encrypt? ";
    std::getline(std::cin, Input);   

    //create named shared memory
    HANDLE shmMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, 
                                            PAGE_READWRITE, 0, 256, _T("shared_mem"));

    //view the mapped memory (makes adress space visible)
    LPCTSTR shmBuffer = (LPTSTR)MapViewOfFile(shmMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 256);

    //Copy Input into shared memory. c_str converts string to pointer to char array
    CopyMemory(shmMapFile, Input.std::string::c_str(), 256);

I suppose it has to do with pointers, but I could not find the cause of the error. So where did I go wrong? Or do I use the functions incorrectly?

Thanks in advance!

Edit: Changing 256 to the actual size of Input didn't help

Edit 2: I tried to minimalize the problem so you can run it yourself:

#include <iostream>
#include <windows.h>
#include <tchar.h>

int main()
{
    char buffer[6] = "Hello";

    HANDLE shmMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,  
        PAGE_READWRITE, 0, 6, _T("shared_mem"));
    if (!shmMapFile == 0)
        std::cout << shmMapFile << "(CreateFileMapping) Error: "<< GetLastError() << std::endl;


    LPCTSTR shmBuffer = (LPTSTR)MapViewOfFile(shmMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 6);
    if(!shmBuffer == 0)
        std::cout << shmBuffer << "(MapViewOfFile) Error: " << GetLastError() << std::endl;


    if (!CopyMemory(shmMapFile, buffer, 6) == 0)
        std::cout << "(CopyMemory) Error: " << GetLastError() << std::endl;

} 

1 answer

  • answered 2020-05-22 14:21 Seva Alekseyev

    The first argument to CopyMemory should be shmBuffer, not the handle. HANDLE is superficially a pointer datatype, but dereferencing it is a sure way to get access violation.