大佬教程收集整理的这篇文章主要介绍了(C)如何写入/读取mmap返回的内存地址?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我们的教授希望我们建立一个自定义的malloc和free,一个使用伙伴分配.他没有乱用堆,而是希望我们只使用mmap从操作系统请求1 GiB的空间:
@H_998_9@mAX_MEM = 1 << 30. void * base = mmap(NULL,MAX_MEM,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANON,0);
每个内存块应该有一个标头,如果内存为空,则通过链表指向下一个和前一个空闲块.
@R_116_6618@说“我想把这些具体数据放在这个特定的地方.”我想象一个免费的块在内存中看起来像这样:
[Occupancy (1 bit)][Size (7 bits)][prev pointer (8 bytes)][next pointer (8bytes)][junk]
所以,让我们说整个1 GiB是免费的.伪代码:
Occupancy = 0; // 0 if empty,1 if allocated Size = 0011110; // where size in bytes = 2^Size next = NULL; prev = NULL; //note that these are part of a struct called mallocList
我如何在我想要的地址创建这些变量?
我试过这个,
int MAX_MEM = 1 << 30; base = mmap(NULL,0); *((unsigned char*) basE) = 0x1E; struct mallocList* temp; temp->prev = NULL; temp->next = NULL; void* tempaddr = base + 1; *((struct mallocList*) tempaddr) = *temp; munmap(base,1 <<30);
printf("%c",*basE); //line 37 struct mallocList* two; two->prev = NULL; two->next = NULL; tempaddr->next = *two; //line 41
编译说,
3.c:37: warning: dereferencing ‘void *’ pointer 3.c:37: error: invalid use of void expression 3.c:41: warning: dereferencing ‘void *’ pointer 3.c:41: error: request for member ‘next’ in something not a structure or union
因此,我认为存储数据或检索数据的方法有问题,我非常感谢可以提供的任何帮助.
void *R_61_11845@y_buddy_malloc(int sizE); void my_free(void *ptr); struct mallocList { struct mallocList *prev; struct mallocList *next; } mallocList;
/* You need to tell gcc to pack the struct without padding,* because you want the pointers stored starTing with the second byte,i.e. unaligned. * That's actually fine in *this* case,since they won't cross a cache-line boundary. * They'll be at the beginning of a page,from mmap,and thus the beginning of a cache line. * Modern cpus are fast at handling misaligned loads within a cache line. */ struct __attribute__ ((__packed__)) mem_block { unsigned int occupied:1; unsigned int size:7; // bitfields. Not necessarily a good idea. Just using a signed int yourself might be better. positive for allocated,negative for free. struct mallocList { // nested deFinition. you can do this differently struct mallocList *prev,*next; } pointers; }; // don't need the type-name here. That would declare a variable of the struct type. int MAX_MEM = 1 << 30; void *base = mmap(NULL,0); char *cp = base; cp[0] = size << 1 | 1; // pack the size and occupied bits into a byte struct mallocList *mlp = (struct mallocList*)(cp+1); // This avoids needing a compiler-specific way to pack your struct. // or struct mem_block *mbp = base; mbp->occupied = 1; mbp->size=whatever; mbp->pointers.prev = NULL; mbp->pointers.next = NULL;
抱歉,这可能无法编译,但关于转换指针的基本想法是可靠的.
以上是大佬教程为你收集整理的(C)如何写入/读取mmap返回的内存地址?全部内容,希望文章能够帮你解决(C)如何写入/读取mmap返回的内存地址?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。