Can I replace a call to open_memstream with a malloc and an implicit cast?

后端 未结 2 1629
感动是毒
感动是毒 2021-01-01 00:38

All,

I have a program that prints to a stream. I need to buffer this stream in memory, and then print each line as necessary to an actual file later.

Since t

2条回答
  •  梦谈多话
    2021-01-01 01:41

    No. malloc() just gives you a block of (probably uninitialized) memory. There's no "magical" casting going on; when you do int * buf = malloc(10*sizeof(int); you are pointing buf at, effectively, 10 uninitialized ints.

    The corresponding thing with a FILE would be FILE * f = malloc(10*sizeof(FILE)); which points f at 10 uninitialized FILE structures, which doesn't make any sense. Furthermore, writing to an uninitialized FILE is likely to result in a crash if you're lucky.

    It's easier to help if you tell us what platforms you're targeting and what you actually want to achieve. On POSIX, you can use shm_open() to get a file descriptor pointing to "shared memory" and fdopen() to turn the file descriptor to a FILE*. Yes, it might run out of space.

提交回复
热议问题