奇怪的C堆栈内存覆盖
Weird C stack memory overrides
我正在实现一个版本的malloc和免费练习。因此,我有一个固定长度(10000)的静态字符数组。然后,我实现了一个struct memblock,它保存了块的大小等信息,如果它是空闲的…
我实现malloc的方式是这样的,我把小块(<8字节)放到char数组的前面,大一点的放到另一端。所以,我基本上是用两个链表来连接前面和后面的块。然而,我在初始化列表时遇到了奇怪的问题(在第一次调用malloc时)。
这是我的代码:
#define MEMSIZE 10000 // this is the maximum size of the char * array
#define BLOCKSIZE sizeof(memblock) // size of the memblock struct
static char memory[MEMSIZE]; // array to store all the memory
static int init; // checks if memory is initialized
static memblock root; // general ptr that deals with both smallroot and bigroot
static memblock smallroot, bigroot; // pointers to storage of small memory blocks and bigger blocks
void initRoots(size_t size, char* fileName, int lineNum)
{
smallroot = (memblock)memory;
smallroot->prev = smallroot->next = 0;
smallroot->size = MEMSIZE - 2 * BLOCKSIZE;
smallroot->isFree = 1;
smallroot->file = fileName;
smallroot->lineNum = lineNum;
bigroot = (memblock)(((char *)memory) + MEMSIZE - BLOCKSIZE - 1);
bigroot->prev = bigroot->next = 0;
bigroot->size = MEMSIZE - 2 * BLOCKSIZE;
bigroot->isFree = 1;
bigroot->file = fileName;
bigroot->lineNum = lineNum;
init = 1;
}
我使用GDB来查看我在哪里得到segfault。当bigroot->next = 0时;是执行。这将把smallroot设置为0。哪个更奇怪?如果我设置bigroot->next = 0x123,那么smallroot就变成0x1。如果我设置0x1234,那么它就变成了0x12。它将smallroot设置为bigroot->next的值,不包括其最后两位。我真的不明白这是怎么发生的!
这是memblock的定义:
typedef struct memblock_* memblock;
struct memblock_ {
struct memblock_ *prev, *next; // pointers to next and previous blocks
/* size: size of allocated memory
isFree: 0 if not free, 1 if free
lineNum: line number of user's file where malloc was invoked
*/
size_t size, isFree, lineNum;
char* file; // user's file name where the block was malloced
};
#define BLOCKSIZE sizeof(memblock) // size of the memblock struct
你想:
#define BLOCKSIZE sizeof(*memblock) // size of the memblock_ struct
这里的-1
也是假的(创建错误对齐的指针):
bigroot = (memblock)(((char *)memory) + MEMSIZE - BLOCKSIZE - 1);
实际上,我将指向memblock的指针存储在内存数组中。memblock的值存储在栈中
不,他们不是。smallroot
和bigroot
明显指向数组本身。
相关文章:
- C++自动内存 malloc 和免费覆盖问题
- 内存覆盖在我自己的 Vector 类中
- 使用放置 new 覆盖内存中的对象
- 用new分配4k int后的内存覆盖
- 初始值设定项列表覆盖动态多维数组的内存
- 内存将被代码中的溢出覆盖
- 动态分配的内存-C 覆盖
- 销毁时执行自动内存覆盖的模板
- 如何使用 CUDA 推力执行策略覆盖推力的低级设备内存分配器
- 通用内存分配崩溃,用于覆盖C++中的新建和删除
- 内存映射文件,保护单个视图不被覆盖
- 将DWORD写入内存只覆盖1个字节,而不是4个字节
- 当我们开始覆盖内存时,对象的生命周期是否已经结束?
- 设计一个内存覆盖检测工具
- 奇怪的C堆栈内存覆盖
- 如何覆盖一般malloc,所以我得到行号打印在内存泄漏打印输出
- C++ strncpy 参数 "optimized out" ;覆盖随机内存
- 什么是覆盖共享内存
- 卡洛克覆盖了另一个变量的内存?
- 分配结构数组后覆盖的内存