c++ - 即使分配了内存,Memcpy 分段错误
问题描述
我试图通过将数据写入内存来从一个文件中复制数据,然后使用 memcpy 将其复制到另一个文件中,但我很难过。我无法让它停止给我分段错误。我感觉它与分配的内存有关,但我也确保输出文件的文件大小与第一个相同,因此它不会有这个问题并且可以将数据粘贴到其中。
编辑:我开始认为它与 char out_data 以及当它是只读的时我如何尝试将数据复制到其中有关。不知道该怎么做。
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <chrono>
using namespace std;
using namespace std::chrono;
#define OUTPUT_MODE 0700 // protection bits for output file
int main(int argc, char** argv)
{
auto start = high_resolution_clock::now();
/* Open the specified file */
int fd = open(argv[1], O_RDWR);
// stats.st_size is a variable containing the size of inFile.txt
struct stat instats;
if (stat(argv[1], &instats)==0)
cout<<endl<<"inFile size "<<instats.st_size;
else
cout<<"Unable to get file properties.\n";
/* Get the page size */
int pagesize = getpagesize();
cout<<endl<<"page size is " <<pagesize<<"\n";
/******************Creation of outFile.txt******************/
int out_fd = creat(argv[2], OUTPUT_MODE);
char* in_data = (char*)mmap(NULL, instats.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
ftruncate(out_fd, instats.st_size);
char* out_data = (char*)mmap(NULL, instats.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, out_fd, 0);
// THIS LINE IS THE CULPRIT
memcpy(out_data, in_data, instats.st_size);
/* Unmap the shared memory region */
munmap(in_data, instats.st_size);
munmap(out_data, instats.st_size);
/* Close the file */
close(fd);
close(out_fd);
return 0;
}
解决方案
creat
创建一个只为写入而打开的文件。您不能mmap
使用这样的文件描述符,因为不存在只写内存之类的东西。如果您要检查 of 的返回值mmap
,out_fd
您会发现它失败了,并且errno == EACCES
. 当mmap
失败时,它返回一个无效的指针MAP_FAILED
(不是 NULL,但通常是),当尝试在那里写入-1
时会导致段错误。memcpy
请注意,这if (!out_data)
是对mmap
;失败的错误测试。你必须使用if (out_data == MAP_FAILED)
.
而不是creat
,使用open(argv[2], O_RDWR | O_CREAT | O_TRUNC, OUTPUT_MODE)
.
推荐阅读
- php - curl 中的 API 密钥
- swift - 有没有办法消除 SwiftUI 中填充的外边缘?
- sql - 如何聚合维度变化缓慢的数据
- python - 在 MAP 函数中使用 for 循环
- sql - 使用 EXISTS 指令是否改进了这个查询
- python - 是否有任何选项可以检查 URL 是否有效?在将它传递给 scrapy 中的下一个函数之前,Python
- spring - 使用 @EventListener 的 Spring ExitCodeEvent 不起作用
- python - 如何将其更改为超链接?不和谐.py
- python - 向 numpy 数组添加偏差
- php - 从 url 获取文本数据并刷新它