简体   繁体   English

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

[英]Can I reuse the buffer in open_memstream

When working in a loop, I'd like to re-use the already allocated buffer multiple times:在循环中工作时,我想多次重用已分配的缓冲区:

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!
}

Is this possible?这可能吗? Or will this lead to UB?或者这会导致UB?

No, you can't do this with open_memstream , but doing so won't lead to UB, but rather a memory leak.不,你不能用open_memstream做到这open_memstream ,但这样做不会导致 UB,而是内存泄漏。 man 3 open_memstream says "The function dynamically allocates the buffer" and "After closing the stream, the caller should free(3) this buffer." man 3 open_memstream说“函数动态分配缓冲区”和“关闭流后,调用者应该释放(3)这个缓冲区。” Your code as written will overwrite membuf each iteration of the loop with a new allocation, preventing you from ever freeing the old ones.您编写的代码将在循环的每次迭代中覆盖membuf ,并使用新的分配,防止您释放旧的。 It won't reuse the old allocation, as you seemed to hope it would.它不会像您希望的那样重用旧的分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM