miroki123 miroki123 - 2 months ago 17
C Question

fprintf printing garbage to txt file

I'm having trouble with strings and c.

I'm trying to do something very simple: converting an int into a string and printing it into a txt file in the following fashion.

const char * test_string() {
char s[5];
int num = 123;
sprintf(s, "%d", num);
return s;

int save() {
FILE *fh = fopen("test.txt", "w");
const char * text = test_string();
fprintf(fh, "%s", text);

Yet, for this simple task, I'm getting the following result:


I'd like some assistance with this problem. Thanks in advance.


s is a local variable in test_string, so it is destroyed when test_string returns. Then, you try to print the value of a variable that no longer exists.