所以我正在研究一个小的内存分配包,我想要指针的初始化来保存分配空间的大小以及它是通过我的一个函数分配的指示器(这是内存中大小之前的字符“q”)。因此,我尝试执行以下操作:
int qmem_alloc(unsigned num_bytes, void ** rslt){
*rslt = malloc(num_bytes+sizeof(int)+sizeof(char));
*((int*)rslt) = num_bytes;
*(char*)(rslt+sizeof(int)) = 'q';
rslt = rslt+sizeof(int) + sizeof(char);
if(*rslt == NULL)
return -1;
else if(errno != 0){
//Catch the rest of the errors
return -2;
}
return 0;
}
但是,在我的main函数中,好像rslt地址前的内存传回后没有包含它应该包含的内容。我在这里通过更改指针地址做坏事吗?
最佳答案
您在某些地方缺少一定程度的间接访问。在取消引用之前使用 rslt
的任何地方都应该使用 *rslt
:
int qmem_alloc(unsigned num_bytes, void ** rslt){
*rslt = malloc(num_bytes+sizeof(int)+sizeof(char));
if(*rslt == NULL)
return -1;
*((int*)*rslt) = num_bytes;
*(char*)(*rslt+sizeof(int)) = 'q';
*rslt = *rslt+sizeof(int) + sizeof(char);
if(errno != 0){
//Catch the rest of the errors
return -2;
}
return 0;
}
此外,malloc
返回的内存已正确对齐以供任何使用。因为您返回 sizeof(int)+sizeof(char)
== 5 个字节(假设一个 4 字节 int
),这意味着您返回的指针可能不是。您需要至少再添加 3 个字节以将返回的缓冲区放在 8 字节的边界上。
关于c - 通过 malloc 故意隐藏内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52671052/