When we return from function, if return value is a pointer, it must be define as static. Is this true for heap memory allocated pointer (such as new
/malloc
pointers),too?
consider this example:
#include"stdio.h"
char * func()
{
char * X=new char[10];
X[0]='C';
x[1]='\0';
return X;//is it a good return from function?
}
main()
{
char * A=func();
puts(A);
delete[] A;
}
As others already pointed out, technically, the code is okay.
However, the real problem with the code is the function signature char * func()
.
It only specifies that it will return a pointer to a char. That pointer can be
The pointer can point to
There is no way of knowing what to do unless you want to trust the documentation or to investigate in possibly a lot of code (functions calling functions calling functions...).
This can be avoided by returning
Manual memory management is hard to get right within a complete application and should never be your main concern, so it should be avoided and not hidden by functions returning pointers.
Besides the weird increment/decrement fiddling, the code is okay.
The variable X
goes out of scope when the function returns, but that's only the actual variable and not what it points to.
Pointers are basically simple integers, whose contents just happens to be an address to somewhere in memory, and treated specially by the compiler. What happens when the function returns is that the contents of the variable X
is copied before the variable goes out of scope. Then the copy of the contents (the actual memory address) is again copied, this time to the variable A
in the calling function.
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