指针算术导致错误的地址写入

Here I am attempting to write the address of next block_t at the address where the previous block has its payload structure. This is just a PoC that I'm testing to integrate into my main code later on. However, instead of writing the address to the next block, it writes address to itself as you will notice when you see the output.

编辑1:所以我想问题现在归结为“如何重用为有效负载分配的指针以指向另一个块?”

#include <stdio.h>
#include <stdlib.h>

typedef unsigned word_t;

typedef struct block {
    word_t header;
    char payload[0];
} block_t;

static void set_next_free_block(block_t *block, block_t *nblock) {

    // Store the address of next block at the location where payload starts
    word_t *next_address = (word_t *)(block->payload);

    // Now write the address of next block here
    *next_address = nblock;

    return;
}

static block_t *get_next_free_block(block_t *block) {

    block_t *next_address = (block_t *)((word_t *)block->payload);

    return next_address;
}

int main() {
    block_t *block = (block_t *)malloc(sizeof(block_t));
    block_t *nblock = (block_t *)malloc(sizeof(block_t));
    block_t *next = NULL;
    set_next_free_block(block, nblock);
    next = get_next_free_block(block);
    printf("Block 1\nBlock address: %16x\n", (word_t)block);
    printf("Payload address: %16x\n", (word_t)block->payload);
    printf("Next: %16x\n", (word_t)next);
    printf("Block 2\nBlock address: %16x\n", (word_t)nblock);

    return 0;
}

I don't understand why the address added which I set inside set_next_free_block to point to address of nblock points to the wrong address.

运行此命令时,我得到:

Output of above code

评论