I am writing a program that reads a value from an .ini file, then passes the value into a function that accepts a PCSTR (i.e. const char *). The function is getaddrinfo()
.
So, I want to write PCSTR ReadFromIni()
. To return a constant string, I plan on allocating memory using malloc()
and casting the memory to a constant string. I will be able to get the exact number of characters that were read from the .ini file.
Is that technique okay? I don't really know what else to do.
The following example runs fine in Visual Studio 2013, and prints out "hello" as desired.
const char * m()
{
char * c = (char *)malloc(6 * sizeof(char));
c = "hello";
return (const char *)c;
}
int main(int argc, char * argv[])
{
const char * d = m();
std::cout << d; // use PCSTR
}
The second line is "horribly" wrong:
You are assigning variable
c
twice, so obviously, the first assignment has no meaning. It's like writing:On top of that, you "lose" the address of the allocated memory, so you will not be able to release it later.
You can change this function as follows:
Keep in mind that whoever calls
char* p = m()
, will also have to callfree(p)
at some later point...NO. This is not OK. When you do
the memory allocated by
malloc
lost.You can do as
One way is to return a local static pointer.
This way, whenever the next time
m()
is called,c
still points to the memory block allocated earlier. You could reallocate the memory on demand, fill in new content, and return the address.