gpt4 book ai didi

c - mmap: map_anonymous 为什么它给 SIGSEGV?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:16:02 27 4
gpt4 key购买 nike

为什么这段代码会报segmentation fault?

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>

int main()
{
void *ptr;

ptr=mmap(NULL, 10, PROT_READ|PROT_WRITE, MAP_ANONYMOUS, -1, 0);
strcpy(ptr, "Hello");

}

或者更好的是,我希望:char *ptr=malloc(10); 然后将此参数传递给 mmap。两者都给出 SIGSEGV。

最佳答案

检查系统调用的返回值!

mmapflags 参数必须恰好具有以下两个选项之一:

MAP_SHARED
Share this mapping. Updates to the mapping are visible to other processes
that map this file, and are carried through to the underlying file. The file
may not actually be updated until msync(2) or munmap() is called.

MAP_PRIVATE
Create a private copy-on-write mapping. Updates to the mapping are not
visible to other processes mapping the same file, and are not carried through
to the underlying file. It is unspecified whether changes made to the file
after the mmap() call are visible in the mapped region.

你没有提供它,所以 mmap 很可能失败(返回 (void*)-1),errno 设置为EINVAL.

关于c - mmap: map_anonymous 为什么它给 SIGSEGV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8616746/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com