合并内存并处理 C 中的指针运算

标签 c pointers memory memory-management

在下面的代码中,不知道为什么从来不输入if。对我来说,它在 if 中是有意义的:

void Mem_Coalesce(){


    list_t* temp;
    temp = freep;
        if(free_node_count == 2){
        //will finish
             printf("Addr of temp is  %llx\n\n", (long long unsigned) temp);
                 printf("Size of Temp is  %d\n\n", temp->size);
             printf("Addr of end of temp free node space is  %llx\n\n", (long long unsigned) ((char*)temp + temp->size));
             printf("Addr of start temp->next  is  %llx\n\n", (long long unsigned) temp->next);
        if( ((char*)temp + (temp->size)) == (char*)(temp->next)){
                printf("Entered the if statement\n");
                        temp->size += (temp->next)->size;
                temp->next = NULL;
        }


    }else {

        while(temp->next != NULL  ){

            if( ((char*)temp + (temp->size)) == (char*)(temp->next)){

                temp->size += (temp->next)->size;
                                printf("coalesced size is %d temp->size \n", temp->size);
                temp->next = (temp->next)->next;
                ((temp->next)->next)->prev = temp;
            }
            temp=temp->next;

        }

    }



}

结果是

Addr of temp is  7f9c1e89b070

Size of Temp is  200

Addr of end of temp free node space is  7f9c1e89b138

Addr of start temp->next  is  7f9c1e89b278

如您所见,它永远不会进入 if 语句。另外让我知道是否有任何其他更有效的内存合并算法。

最佳答案

您在这里以十进制打印 temp->size:

printf("Size of Temp is  %d\n\n", temp->size);
                         ^^

当您以十六进制打印出指针值时:

printf("Addr of temp is  %llx\n\n", (long long unsigned) temp);
                         ^^^^ 

200 十进制是 C8 的十六进制和 0xC8 + 0x70 = 0x138 .因此,当您将 0xC8 添加到 0x7f9c1e89b070 时,结果是 0x7f9c1e89b138 不等于 0x7f9c1e89b278 因此您不会输入if 语句。

关于合并内存并处理 C 中的指针运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19439829/

相关文章:

c++ - std::sort 使用继承的仿函数

c - 如何回答这个关于常量指针的面试测试?

linux - 使用 SIGALRM 和计时器时内存损坏

c++ - 为什么要设计自定义内存管理器?

c - 访问双链表结构体的字段

c - getaddrinfo 何时返回列表中的多个 sockaddr 结构?

c - 为什么这个数组大小 "workaround"给我一个警告?

c++:通过指针访问主类的std::vector的类出错

java - "non-zero"基元的数组是否需要更多内存?

c - 我的 wcf 端点出现问题