我可以重用 open_memstream 中的缓冲区吗

Can I reuse the buffer in open_memstream

在循环中工作时,我想多次重复使用已分配的缓冲区:

char *membuf = NULL;
size_t size = 0;
while(1) {
    FILE *f = open_memstream(&membuf, &size);

    uint8_t iobuf[8192];
    int32_t readbytes = 0;

    // some I/O here
    while(readbytes = read(/*some I/O params here*/) != 0) {
        fwrite(iobuf, sizeof(uint8_t), readbytes, f); 
    }

    fclose(f);

    // process message, once done, loop for next message
    // explicitly NO free of membuf!
}

这可能吗?或者这会导致 UB 吗?

不,您不能使用 open_memstream 执行此操作,但这样做不会导致 UB,而是会导致内存泄漏。 man 3 open_memstream says "The function dynamically allocates the buffer" and "After closing the stream, the caller should free(3) 这个缓冲区。”你写的代码将用新的分配覆盖 membuf 循环的每次迭代,防止你释放旧的。它不会重用旧的分配,因为你似乎希望如此。