简体   繁体   English

如何像malloc一样使用mmap?

[英]How to use mmap like malloc?

I'm trying to allocate memory for 10x of my list struct then use it for my linked list but I keep getting a segmentation fault.我正在尝试为我的列表结构的 10x 分配内存,然后将它用于我的链表,但我不断收到分段错误。

Valgrind瓦尔格林德

==3806== Invalid write of size 4
==3806==    at 0x4005FD: main (comp.c:14)
==3806==  Address 0xffffffffffffffff is not stack'd, malloc'd or (recently) free'd

Sample Code示例代码

#include <sys/mman.h>

typedef struct list {
    int num;
    struct list *next;
}list;

int main()
{
    list *nodes = mmap(NULL, sizeof(list) * 10, PROT_READ | PROT_WRITE, MAP_PRIVATE, -1, 0);

    nodes[0].num = 1;
    nodes[0].next = NULL;

}

The 0xffffffffffffffff almost surely means that mmap failed. 0xffffffffffffffff几乎肯定意味着mmap失败。 If you want to use it to allocate memory like malloc , you have to do error checking just as you would for malloc , except that you need to test the returned value against MAP_FAILED instead of NULL .如果你想用它来像分配内存malloc ,你所要做的错误检查就像你的malloc ,除非你需要测试对返回的值MAP_FAILED而不是NULL

The failure is probably because you are trying to map a nonexistent file descriptor -1 .失败可能是因为您试图映射不存在的文件描述符-1 This is only allowed when the MAP_ANONYMOUS flag is specified, which you did not include.这仅在指定了MAP_ANONYMOUS标志时才允许,您未包括该标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM