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?
No, you can't do this with open_memstream
, but doing so won't lead to UB, but rather a memory leak. man 3 open_memstream
says "The function dynamically allocates the buffer" and "After closing the stream, the caller should free(3) this buffer." Your code as written will overwrite membuf
each iteration of the loop with a new allocation, preventing you from ever freeing the old ones. It won't reuse the old allocation, as you seemed to hope it would.