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

时间:2013-10-18 00:55:16

标签: 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 statement。如果还有其他任何可能更有效的内存合并算法,请告诉我。

1 个答案:

答案 0 :(得分:2)

您在此处以小数形式打印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 语句。< / p>