const char* test(bool i)
{
const char t[] = "aa\n";
const char* p = "bbb\n";
if(i)
return p;
return t;
}
int main(array<System::String ^> ^args)
{
printf(test(true));
printf(test(false));
return 0;
}
That returns something of sort:
bbb
%^&$^$%
It is clear that test(false) returns a pointer to a local variable. The question is that p is also local variable. Why the memory for “bbb\n” is not cleaned after the function returns. I thought const char[] is interpreted same way as const char* but it is not true as it seems.
pis a local variable, which you return by value, but points to a string literal, which resides in read-only memory, not in the automatic memory allocated for the method.Returning
tand the using it indeed results in undefined behavior.Also, don’t think of pointers and arrays to be equivalent.