ciocstring

fmemopen not writing to c-string


I cannot get fmemopen to print to a cstring consistently. Doing something like this:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char buf[256];
    FILE *out;

    out = fmemopen(buf, strlen(buf), "w");
    fprintf(out, "Hello world");
    fclose(out);
    puts(buf);

    return 0;
}

Only yields 'H' being output.

I tried used open_memstream

#include <stdio.h>
#include <string.h>

int main(void)
{
    char *buf;
    int buf_size;
    FILE *out;

    out = open_memstream(&buf, &buf_size);
    fprintf(out, "Hello world");
    fflush(out);
    puts(buf);
    free(buf);
    fclose(out);

    return 0;

}

This seems to work, but in other contexts it appears to segfault.

How can I get fmemopen to work consistently and/or how am I losing track of the value of the pointer returned from open_memstream?

EDIT: I see how I'm getting segfaults with open_memstream after taking a closer look at my code. I still want to know why fmemopen doesn't work though.


Solution

  • According to your first piece of code:

    Calling strlen(buf) invokes undefined behaviour, as the contents of buf isn't defined. Use sizeof(buf) instead.