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

标签 c debugging pointers memory-management pointer-arithmetic

我正在用 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/

相关文章:

c - 在 wav 文件的整数样本上移动频率(使用 FFT)

Linux Makefile 项目调试最佳实践和工具

Android Debug Bridge (adb) 设备 - 无权限

C:从函数返回指针数组的元素

c++ - 使用对象指针时如何访问成员函数

C、getc/fgetc - 终端 null

C - RSA 加密系统解密问题(unsigned long long 不够大?)

c - 调试崩溃的用 OpenWatcom 编译的 32 位 DOS 可执行文件

c - 在函数调用期间将哪些值压入堆栈?

c - 在 C 中将时间戳存储为二进制分数