- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我实现了一个自定义的内存分配器。我为此内部文件memory.c
编写的所有主要代码都在该文件中创建了一个主要功能以测试功能。一切正常。但是,当我将这些测试代码移动到另一个文件(调用main.c
并运行它。遇到分段错误)。
int main (int argc, char *argv []) {
allocator_init();
char* ptr = (char*) allocate(4096); // csutom function. that on `memory.c`
strcpy(ptr, "this is the test one");// segmentation fault here
printf("print: %s\n", ptr);
deallocate(ptr);
}
volatile Memory memory;
/* allocated memory to memory variable by assign /dev/zero to memory */
void allocator_init() {
fd = open("/dev/zero", O_RDWR);
if(fd == -1) {
perror("File open failed");
exit(0);
}
// page size can different on different platform. customize again to optimize
PAGE_SIZE = getPageSize();
// fd = open("ZEROES", O_RDWR);
if(fd == -1) {
perror("File open failed");
exit(0);
}
// Initialize the region list
memory.region = NULL;
int i;
/// Initialize the caches
/// size of each cache is 16 * 2^i => 16, 32, 64, 128, 256, 512, 1024, 2048
for (i=0; i<8; i++) {
memory.cache[i].size = 16<<i;
memory.cache[i].S = NULL;
}
return;
}
void *allocate_region (unsigned int size) {
Region *region, *temp;
temp = memory.region;
void *mapped_addr = mmap(NULL, size + REGION_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
if(mapped_addr == MAP_FAILED) {
perror("Mapping failed");
exit(0);
}
/* create region from mapped address */
region = mapped_addr;
region->size = size;
region->addr = mapped_addr + REGION_SIZE;
printf("allocated region: %p\n", region->addr);
/* assign this region to memory */
memory.region = region;
/* just simple append algorithm in linked list. so new region will be appended to head of linked list */
region->next = temp;
return region->addr;
}
/* allocate : if size < 2048 : allocate cache. else allocate region */
void *allocate(unsigned int size) {
size = ALIGN(size);
return allocate_region(size);
}
memory.h
定义我使用过的所有结构:
#ifndef MEMORY_H
#define MEMORY_H
#define MAX_SIZE (1024*1024)
#define REGION_SIZE sizeof(Region)
#define SLAB_SIZE sizeof(Slab)
#define WORD_SIZE 32
#define ALIGNMENT 8
/* rounds up to the nearest multiple of ALIGNMENT */
#define ALIGN(size) (((size) + (ALIGNMENT-1)) & ~0x7)
#define SIZE_T_SIZE (ALIGN(sizeof(size_t)))
#define TRUE 1
#define FALSE 0
#define MAX_SIZE 10000
// Caches are:
// 16, 32, 64, 128, 256, 512, 1024, 2048
#include "bits.h"
int PAGE_SIZE;
// File descriptor for zeroes file
int fd;
void allocator_init();
int deallocate_cache(void* ptr);
void *allocate(unsigned int size);
typedef struct __Region {
void *addr; /// started address can use for caller (can calc by allocated address + Region size)
int size; /// size of this allocated Region (not include size Region)
struct __Region *next;
} Region;
/// size of Slab equals to size of System Page
typedef struct __Slab {
void *addr; /// address of this slab (exclude header)
char *bitmap; /// started address can use for caller (can calc by allocated address + slab size)
int size;
int slots; /// number of slots in maximum has been used
int cache_size; /// size of cache that contains this slab
int bitmap_size; /// size of bitmap. so, can count address bit by bitmap + bitmap_size
int currentSize; /// current allocated elements of this slab. currentSize = 0. deallocated this slab
int bit; /// bit to marked which part of slab has been used
struct __Slab * next;
} Slab;
typedef struct __Cache {
int size;
Slab *S;
} Cache;
typedef struct __Memory {
Region *region;
Cache cache[8];
} Memory;
#endif // MEMORY_H
allocate
函数返回一个地址。移动到另一个文件时遇到错误。在我的
memory.c
中,我有一些全局变量来控制分配的地址和内存。将代码移到新文件时会影响吗?我无法解释这一点。
最佳答案
有一些值得观察的发现:
allocator_init()
,allocate()
和deallocate_cache()
。文件中的其他所有内容都是实现细节,应从代码使用者中隐藏。 extern
,则应在其前面加上static
,您最好有一个很好的理由。 (有关详细信息,请参见How do I share a variable between source files in C。)_
开头的名称,以供实现使用。这有点过分简化,但是它涵盖了所有基础,并且比形式正确的规则更容易记住。以__
开头的名称绝对是禁止使用的(100%;不涉及任何简化)。不要为自己定义这样的名称,并且要非常谨慎地在代码中使用这样的名称(它们通常是您不应该使用的类型)。我只是从结构标签中删除了下划线。它工作愉快。 "bits.h"
,但是幸运的是您的代码未使用其中的任何内容,因此将其注释掉是可以的。 getPageSize()
,但未定义它。可能是可以原谅的;我改用4096。并跟踪下来表明PAGE_SIZE
是标头中定义的变量,导致此diatribe辩论开始,说明了要做什么。它应该是static
文件中的memory.c
变量。从源文件外部可见的唯一内容应该是使用者需要使用的那些函数(也许还有全局变量)。其他所有内容均应为static
,以使其不可见-名称不冲突,不存在滥用或滥用的可能性。 PAGE_SIZE
未使用。顺便说一句,这是将所有可以静态化的内容变成静态定义的另一个优点-当由于非静态而可以在源代码外部访问代码时,编译器不会警告未使用的变量或函数。 MAX_SIZE
定义了两个不同的值;别! #define TRUE 1
;再次,不要。 (也没有使用MAX_SIZE
,也没有使用FALSE
,也没有使用SLAB_SIZE
,...)ALIGN
宏有故障: #define ALIGN(size) (((size) + (ALIGNMENT - 1)) & ~0x7)
& ~(ALIGNMENT - 1)
。当心明显的参数化是不完整的。 EXIT_FAILURE
-或遵循其他一些与本地相关的方案。 deallocate_cache()
,但是您的主程序调用了deallocate()
,但没有给出两者的代码。命名不一致是有问题的。我使用了一个虚拟实现。 Mapping failed: Operation not supported by device
./dev.zero
并引用它来解决此问题。当心可移植性假设。
allocated region
消息。这样可以将损坏限制在3行代码之内。
void *
类型进行算术运算。但是,在具有任何可移植性的代码中,请不要利用它。
dd if=/dev/zero of=dev.zero bs=1k count=1024
将文件初始化为全零时,该程序不再崩溃。我添加了一堆调试打印代码。
/dev/zero
用于映射文件。
Mapping succeeded: 0x10ca74000
region = 0x10ca74000
size = 4096
allocated region: 0x10ca74018
Memory: allocate_region (0x10ca40080)
Region: Base (0x10ca74000)
Address: 0x10ca74018, size: 4096, next = 0x0
Cache: line 0 (0x10ca40088)
Size: 16
Cache: line 1 (0x10ca40098)
Size: 32
Cache: line 2 (0x10ca400a8)
Size: 64
Cache: line 3 (0x10ca400b8)
Size: 128
Cache: line 4 (0x10ca400c8)
Size: 256
Cache: line 5 (0x10ca400d8)
Size: 512
Cache: line 6 (0x10ca400e8)
Size: 1024
Cache: line 7 (0x10ca400f8)
Size: 2048
ptr = 0x10ca74018
print: this is the test one
deallocate called for 0x10ca74018: unimplemented
#ifndef MEMORY_H
#define MEMORY_H
extern void allocator_init(void);
extern void deallocate(void *ptr);
extern void *allocate(unsigned int size);
#endif // MEMORY_H
#include <stdio.h>
#include <string.h>
#include "memory.h"
int main(void)
{
allocator_init();
char *ptr = (char *) allocate(4096); // custom function. that on `memory.c`
printf("ptr = %p\n", ptr);
strcpy(ptr, "this is the test one"); // segmentation fault here
printf("print: %s\n", ptr);
deallocate(ptr);
}
#include "memory.h"
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
#define REGION_SIZE sizeof(Region)
#define ALIGNMENT 8
#define ALIGN(size) (((size) + (ALIGNMENT - 1)) & ~(ALIGNMENT - 1))
#if defined(DEV_ZERO_MEMORY_MAPPING)
#define DEV_ZERO "/dev/zero"
#else
#define DEV_ZERO "./dev.zero"
#endif
enum { NUM_CACHES = 8 };
static int fd = -1;
typedef struct Region
{
void *addr;
int size;
struct Region *next;
} Region;
typedef struct Slab
{
void *addr;
char *bitmap;
int size;
int slots;
int cache_size;
int bitmap_size;
int currentSize;
int bit;
struct Slab *next;
} Slab;
typedef struct Cache
{
int size;
Slab *S;
} Cache;
typedef struct Memory
{
Region *region;
Cache cache[NUM_CACHES];
} Memory;
static Memory memory = { 0 };
static void dump_slab(FILE *fp, const char *tag, const Slab *slab)
{
fprintf(fp, "Slab: %s (%p)\n", tag, slab);
if (slab != 0)
{
fprintf(fp, "addr: %p, ", slab->addr);
fprintf(fp, "bitmap: %p, ", (void *)slab->bitmap);
fprintf(fp, "size: %6d, slots %3d, ", slab->size, slab->slots);
/*
int cache_size;
int bitmap_size;
int currentSize;
int bit;
struct Slab *next;
*/
}
}
static void dump_cache(FILE *fp, const char *tag, const Cache *cache)
{
fprintf(fp, "Cache: %s (%p)\n", tag, cache);
if (cache != 0)
{
fprintf(fp, "Size: %d\n", cache->size);
Slab *slab = cache->S;
while (slab != 0)
{
dump_slab(fp, "", slab);
slab = slab->next;
}
}
}
static void dump_region(FILE *fp, const char *tag, const Region *reg)
{
fprintf(fp, "Region: %s (%p)\n", tag, reg);
if (reg != 0)
{
fprintf(fp, "Address: %p, size: %6d, next = %p\n",
reg->addr, reg->size, reg->next);
}
}
static void dump_memory(FILE *fp, const char *tag, const Memory *mem)
{
fprintf(fp, "Memory: %s (%p)\n", tag, mem);
if (mem != 0)
{
Region *reg = mem->region;
dump_region(fp, "Base", reg);
while (reg->next != 0)
{
dump_region(fp, "Next", reg->next);
reg = reg->next;
}
for (int i = 0; i < NUM_CACHES; i++)
{
char line[32];
snprintf(line, sizeof(line), "line %d", i);
dump_cache(fp, line, &memory.cache[i]);
}
}
}
void allocator_init(void)
{
fd = open(DEV_ZERO, O_RDWR|O_CREAT, 0600);
if (fd == -1)
{
perror("File open failed");
exit(0);
}
if (fd == -1)
{
perror("File open failed");
exit(0);
}
memory.region = NULL;
for (int i = 0; i < NUM_CACHES; i++)
{
memory.cache[i].size = 16 << i;
memory.cache[i].S = NULL;
}
}
static void *allocate_region(unsigned int size)
{
assert(fd != -1);
Region *temp = memory.region;
void *mapped_addr = mmap(NULL, size + REGION_SIZE, PROT_READ | PROT_WRITE,
MAP_PRIVATE, fd, 0);
if (mapped_addr == MAP_FAILED)
{
perror("Mapping failed");
exit(0);
}
printf("Mapping succeeded: %p\n", mapped_addr);
Region *region = mapped_addr;
printf("region = %p\n", region);
region->size = size;
printf("size = %d\n", region->size);
region->addr = (char *)mapped_addr + REGION_SIZE;
printf("allocated region: %p\n", region->addr);
memory.region = region;
region->next = temp;
dump_memory(stderr, __func__, &memory);
return region->addr;
}
void *allocate(unsigned int size)
{
size = ALIGN(size);
return allocate_region(size);
}
void deallocate(void *ptr)
{
fprintf(stderr, "%s called for %p: unimplemented\n", __func__, ptr);
}
dump_memory()
,
dump_region()
,
dump_cache()
和
dump_slab()
函数转储复杂的结构;它们通常非常有帮助,尽管它们实际上在调试时有些麻烦。
关于c - C:将主要功能移至新文件时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22885179/
我已经使用 vue-cli 两个星期了,直到今天一切正常。我在本地建立这个项目。 https://drive.google.com/open?id=0BwGw1zyyKjW7S3RYWXRaX24tQ
您好,我正在尝试使用 python 库 pytesseract 从图像中提取文本。请找到代码: from PIL import Image from pytesseract import image_
我的错误 /usr/bin/ld: errno: TLS definition in /lib/libc.so.6 section .tbss mismatches non-TLS reference
我已经训练了一个模型,我正在尝试使用 predict函数但它返回以下错误。 Error in contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]])
根据Microsoft DataConnectors的信息我想通过 this ODBC driver 创建一个从 PowerBi 到 PostgreSQL 的连接器使用直接查询。我重用了 Micros
我已经为 SoundManagement 创建了一个包,其中有一个扩展 MediaPlayer 的类。我希望全局控制这个变量。这是我的代码: package soundmanagement; impo
我在Heroku上部署了一个应用程序。我正在使用免费服务。 我经常收到以下错误消息。 PG::Error: ERROR: out of memory 如果刷新浏览器,就可以了。但是随后,它又随机发生
我正在运行 LAMP 服务器,这个 .htaccess 给我一个 500 错误。其作用是过滤关键字并重定向到相应的域名。 Options +FollowSymLinks RewriteEngine
我有两个驱动器 A 和 B。使用 python 脚本,我在“A”驱动器中创建一些文件,并运行 powerscript,该脚本以 1 秒的间隔将驱动器 A 中的所有文件复制到驱动器 B。 我在 powe
下面的函数一直返回这个错误信息。我认为可能是 double_precision 字段类型导致了这种情况,我尝试使用 CAST,但要么不是这样,要么我没有做对...帮助? 这是错误: ERROR: i
这个问题已经有答案了: Syntax error due to using a reserved word as a table or column name in MySQL (1 个回答) 已关闭
我的数据库有这个小问题。 我创建了一个表“articoli”,其中包含商品的品牌、型号和价格。 每篇文章都由一个 id (ID_ARTICOLO)` 定义,它是一个自动递增字段。 好吧,现在当我尝试插
我是新来的。我目前正在 DeVry 在线学习中级 C++ 编程。我们正在使用 C++ Primer Plus 这本书,到目前为止我一直做得很好。我的老师最近向我们扔了一个曲线球。我目前的任务是这样的:
这个问题在这里已经有了答案: What is an undefined reference/unresolved external symbol error and how do I fix it?
我的网站中有一段代码有问题;此错误仅发生在 Internet Explorer 7 中。 我没有在这里发布我所有的 HTML/CSS 标记,而是发布了网站的一个版本 here . 如您所见,我在列中有
如果尝试在 USB 设备上构建 node.js 应用程序时在我的树莓派上使用 npm 时遇到一些问题。 package.json 看起来像这样: { "name" : "node-todo",
在 Python 中,您有 None单例,在某些情况下表现得很奇怪: >>> a = None >>> type(a) >>> isinstance(a,None) Traceback (most
这是我的 build.gradle (Module:app) 文件: apply plugin: 'com.android.application' android { compileSdkV
我是 android 的新手,我的项目刚才编译和运行正常,但在我尝试实现抽屉导航后,它给了我这个错误 FAILURE: Build failed with an exception. What wen
谁能解释一下?我想我正在做一些非常愚蠢的事情,并且急切地等待着启蒙。 我得到这个输出: phpversion() == 7.2.25-1+0~20191128.32+debian8~1.gbp108
我是一名优秀的程序员,十分优秀!