我的程序应该通过控制台获取输入并使用共享内存,以便另一个进程可以访问该输入。显然CopyMemory
导致分段错误。
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);
我想它与指针有关,但是我找不到错误的原因。那我哪里出问题了?还是我使用的功能不正确?
提前感谢!
编辑:将256
更改为Input的实际大小无济于事
编辑2:我试图将问题最小化,以便您可以自己运行它:
#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;
}
CopyMemory
的第一个参数应该是shmBuffer
,而不是句柄。 HANDLE表面上是指针数据类型,但是取消引用它是获取访问冲突的肯定方法。