c - 地址加 `int`导致int加4次

标签 c memory-management

对于有关操作系统功能的类(class),我们必须为特定大小的结构编写 malloc/free 实现。我们的想法是在该 block 的前几个地址中存储开销,例如我们的代码必须在其中工作的指定(静态)内存块的开始和结束。

但是,最后一个内存槽的计算出了问题;我们将所有可用内存插槽的大小添加到第一个可用内存插槽的地址,以确定最后一个插槽是什么。但是,当将 int sizeofslots 添加到 currentslot 的地址时,它实际上将 sizeofslots 添加到该地址 4 次。这是相关代码:

/* Example memory block*/
/* |------------------------------------------------------------------------------|*/
/* | ovr | 1 t | 0   | 1 t | 1 t | 1 t | 0   | 0   | 0   | 0   | 0   | 0   | 0   |*/
/* |------------------------------------------------------------------------------|*/
/* ovr: overhead, the variables `currentslot`, `firstslot` and `lastslot`.        
 * 1/0: Whether or not the slot is taken.      
 * t: the struct 
 */

/* Store the pointer to the last allocated slot at the first address */
currentslot = get_MEM_BLOCK_START();
*currentslot = currentslot + 3*sizeof(void *);

/* The first usable memory slot after the overhead */
firstslot = currentslot + sizeof(void *);
*firstslot = currentslot + 3*sizeof(void *);

/* The total size of all the effective memory slots */
int sizeofslots = SLOT_SIZE * numslots;

/* The last usable slot in our memory block */
lastslot = currentslot + 2*sizeof(void*);
*lastslot = firstslot + sizeofslots;
printf("%p + %i = %p, became %p\n", previous, sizeofslots, previous + (SLOT_SIZE*numslots), *lastslot);

我们认为它与 4 字节的整数有关,但我们仍然不明白这里发生了什么;谁能解释一下?

最佳答案

C 的指针算法总是这样工作的;加法和减法总是以所指向的项目为单位,不是以字节为单位。

将其与数组索引进行比较:如您所知,对于任何指针 ,表达式 a[i] 等同于 *(a + i) a 和整数 i。因此,加法必须根据 a 的每个元素的大小发生。

要解决它,请在添加之前将结构指针向下转换为 (char *)

关于c - 地址加 `int`导致int加4次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20397360/

相关文章:

c++ - 关于使用 memcpy 将表达式值复制到指针的查询

C++ - 连续内存和多态性

c++ - 京都内阁 TreeDB : memory usage grows uncontrollably until database is closed

android - Volley - 直接下载到文件(没有内存字节数组)

c - 使用管道在父子之间传递整数值

c - 重新索引 Char 中的位

c - Pthread - time.h::sleep() 和 pthread.h::pthread_yield() 有什么区别?

java - 如何从 Android 中的大位图中加载图 block ?

c++ - 表作为从 Lua 调用的 C 函数中的参数

C:将常量字符串转换为常规字符串