Here is an example of what I am trying to do:
#include <stdio.h>
FILE* f;
const char* getstring()
{
f = fopen ("hello.txt", "r");
char x[200];
for (int i = 0; i < 200; i++) x[i] = 0;
for (int c = getc(f), i = 0; (c != EOF) && (i < 200); c = getc(f), i++)
x[i] = c;
fclose(f);
printf ("getstring(): x = %s", x);
const char* y = x;
printf ("getstring(): y = %s", y);
return y;
}
void printstring (const char* string)
{
printf ("%s", string);
}
int main()
{
printstring(getstring());
printf ("\nprintf: %s", getstring());
return 0;
}
and the output is:
getstring(): x = Hello World
getstring(): y = Hello World
���getstring(): x = Hello World
getstring(): y = Hello World
printf: ��������
I don't know why the printstring()
function is outputting nothing and printf
is outputting random data or why there is a bit of random data at the end of the string
when I use the printstring()
function.
Is there any way to fix this and what am I doing wrong?
The problem is that getstring()
returns a pointer to a local array. This array gets destructed when the function returns, so you have an dangling pointer. Using this pointer is then undefined behavior. Anything can happen: for example you can get garbage random value, you can get the old unchanged value, or the system could crash.
Since this question is labelled c++, just use std::string
instead of char*
, and this kind of nightmare will vanish for good.
Note that Using std::string
in prinf()
would require you get a pointer with .c_str()
.
If for an obscure reason, you are required to use char*
you'd have to to use strdup()
or llocate some memory for the c string and return a pointner to that memory. But the caller must then delete this pointer if you don't want memory to leak.
The C string is stored in a function local char array. This array is destroyed when the function is left. Since the question is tagged as C++ use std::string
#include <iostream>
#include <string>
#include <fstream>
std::string getstring()
{
std::ifstream f("hello.txt");
std::string x;
x.resize(200);
for (int i = 0; i < 200; i++) x[i] = 0;
for (int c = f.get(), i = 0; (c != EOF) && (i < 200); c = f.get(), i++)
x[i] = c;
std::cout << "getstring(): x = " << x;
const std::string& y = x;
std::cout << "getstring(): y = " << y;
return x;
}
void printstring (const std::string& string)
{
std::cout << string;
}
int main()
{
printstring(getstring());
std::cout << "\nprintf: " << getstring();
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With