In C programming language, Is it correct to return a local char[] variable by converting it to const char *? -
i understand bad return local variable function stored in stack segment. if convert char[] const char *, return it, considered practice? if so, segment const char * stored in?
something this:
const char * foo() { char str[32]; sprintf(str, "hello"); return (const char *)(str); }
casting const char*
nothing. still points str
value, becomes invalid when return because it's on stack.
adding const
makes whatever uses return value can't modify data pointed pointer (unless cast off const). since points returned function's stack space, once foo
returns, access pointer undefined behavior, point moot.
Comments
Post a Comment