[英]Why am I getting this segmentation fault?
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;
}
This returns a Segmentation Fault 11 这将返回细分错误11
You should check for errors from open
and mmap
. 您应该检查
open
和mmap
错误。 Also, compile with warnings and include the necessary include files. 另外,请编译警告并包括必要的包含文件。
mmap
especially needs a correct prototype on many systems because of its off_t arguments which could break things when you pass it a 0 as a last argument. mmap
特别需要在许多系统上使用正确的原型,因为它的off_t参数可能会在您将0作为最后一个参数传递给它时破坏事情。
But that's not enough. 但这还不够。 Does the file exist and is non-zero size?
该文件是否存在并且大小不为零?
mmap
can happily map pages beyond the end of a file, but access to those pages will result in faults. mmap
可以愉快地将页面映射到文件末尾,但是访问这些页面将导致错误。 If you actually want to the data to be written to the file you need to make sure it's long enough for it. 如果您确实希望将数据写入文件,则需要确保它足够长。 Use
ftruncate
for that. 为此使用
ftruncate
。
Also, I wonder which museum you found your documentation if it mentions caddr_t
as the first argument to mmap
, but that's beside the point, if that compiles it should also work. 另外,我想知道您是否在哪个博物馆找到了文档,如果它提到
caddr_t
作为mmap
的第一个参数,但这caddr_t
,如果可以编译的话也可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.