Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

output wrong #3

Open
lzqyxzh opened this issue Dec 24, 2022 · 1 comment
Open

output wrong #3

lzqyxzh opened this issue Dec 24, 2022 · 1 comment

Comments

@lzqyxzh
Copy link

lzqyxzh commented Dec 24, 2022

the followed code run normal on linux with fmemopen(),but wiht your fmemopen on windows,the output is wrong,can you help to test it,thank you.the result should be "hello,world!".

====code====
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *write_to_buf(char *msg)
{
char *buf = (char *)malloc(1024);

FILE *fp = fmemopen(buf, 1024, "w");
fwrite(msg, 1, strlen(msg), fp);
fclose(fp);

return buf;

}

int main(void)
{
char *str = "hello, world!";
char *buf = write_to_buf(str);

printf("%s\n", buf);

free(buf);

return 0;

}

@GerHobbelt
Copy link

Should work when you either call calloc() or fwrite(msg, 1, strlen(msg) + 1, fp): the point here is that Windows does not zero allocated memory (unless you use calloc(), while many Linuxes do. Your code is theoretically buggy as you forgot to write the NUL string sentinel, so you're riding system-specific and situation-dependent behaviour here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants