我的程序应该通过控制台接受输入,并使用共享内存,以便另一个进程可以访问输入。显然,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更改为输入的实际大小没有帮助
编辑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;
} 发布于 2020-05-22 22:21:07
CopyMemory的第一个参数应该是shmBuffer,而不是句柄。HANDLE表面上是一种指针数据类型,但取消对它的引用肯定会导致访问冲突。
https://stackoverflow.com/questions/61955186
复制相似问题