int main() {
int fd; // File Descriptor for the integer file
int pagesize=getpagesize(); // To store the size of virtual page
printf("\nPage size is %d bytes.\n100 integers require %lu bytes\n",pagesize,100*sizeof(int));
void *data; // This is the pointer which will store the returned pointer when mmap() is called
fd=open("integer", O_RDWR);
data=mmap((caddr_t)0, pagesize, PROT_WRITE | PROT_READ, MAP_SHARED, fd,0);
close(fd);
sprintf((char*)data,"%d",100);
return 0;
}
这将返回一个段错误 11
最佳答案
您应该检查来自open
和mmap
的错误。此外,编译时会出现警告并包含必要的包含文件。 mmap
在许多系统上特别需要一个正确的原型(prototype),因为它的 off_t 参数可能会在你将 0 作为最后一个参数传递给它时破坏事情。
但这还不够。该文件是否存在并且大小不为零? mmap
可以很好地映射超出文件末尾的页面,但访问这些页面会导致错误。如果您真的想要将数据写入文件,您需要确保它足够长。为此使用 ftruncate
。
此外,我想知道您在哪个博物馆找到了您的文档,如果它提到 caddr_t
作为 mmap
的第一个参数,但这不是重点,如果编译它也应该工作。
关于c - 为什么我会收到此段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46683750/