gpt4 book ai didi

c - 当影响 int 的值时明显出现段错误

转载 作者:行者123 更新时间:2023-11-30 19:41:33 25 4
gpt4 key购买 nike

我正在用 C 语言开发内存分配器(从头开始重写 mallocfree)。我使用由 mmap 创建的堆,以及每个内存块之前的 header 来获取有关该 block 的信息。我使用以下结构来处理我的空闲列表(所有空闲 block 的“列表”):

typedef struct node_t {
long int size;
struct node_t *next;
}node_t;

分配新内存块时,我使用临时node_t* temp。我们还有 node_t* startfree 一个指向空闲列表头部的指针。
变量 int size 是包含该部分代码的函数的参数。
bheader_t 是我们稍后将使用的另一个结构。

node_t* temp = (node_t*) (startfree+size+sizeof(bheader_t));
printf("DEBUG : temp %p\n",temp );
printf("DEBUG : startfree %p, size = %ld, next = %p \n",startfree, startfree-> size, startfree -> next );`
printf("DEBUG : future value of temp->size : %ld\n",startfree -> size - size -sizeof(bheader_t));
printf("DEBUG : We want to do temp(%p)->size = startfree(%p)->size (=%ld) - size (=%d) - sizeof(bheader_t) (=%ld)\n", temp, startfree, startfree->size, size, sizeof(bheader_t));
temp -> size = startfree->size - size -sizeof(bheader_t);
printf("DEBUG : temp %p, size : %ld\n",temp,temp->size );
temp -> next = startfree -> next;
startfree = temp;

在某些情况下进展顺利,但在其他情况下,这就是我得到的(在gdb中):

DEBUG : temp 0x7ffff7ff0a0c
DEBUG : startfree 0x7ffff7ef094c, size = 996000, next = (nil)
DEBUG : future value of temp->size : 930452
DEBUG : We want to do temp(0x7ffff7ff0a0c)->size = startfree(0x7ffff7ef094c)->size (=996000) - size (=65536) - sizeof(bheader_t) (=12)

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7bd7a69 in Mem_Alloc_NF (size=65536) at src/nextfit.c:108
108 `temp -> size = startfree->size - size -sizeof(bheader_t);`

简单的 int 行为上的段错误!有什么想法吗?

最佳答案

node_t* temp = (node_t*) (startfree+size+sizeof(bheader_t)); 几乎肯定是错误的。如果 startfree 的类型为 node_t *,那么这会将 (size + sizeof(bheader_t)) * sizeof(node_t) 添加到原始指针。我怀疑你真的想要 node_t* temp = (node_t*) ((char *)startfree+size+sizeof(bheader_t));

关于c - 当影响 int 的值时明显出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33397836/

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