c - Do i must malloc a returned string inside a function? -
this question has answer here:
- string literals: go? 8 answers
the following program print on screen "hello\nworld\n" ('\n' = line down) supposed to. actually, learned, here isn't done should be. "hello" , "world" strings defined inside function (and therefore local , memory released @ end of function's scope - right?). don't malloc them supposed (to save memory after scope). when a() done, isn't memory stack move it's cursor , "world" placed in memory @ same place "hello" ? (it looks doesn't happen here , don't understand why, , therefore, why need malloc if memory block saved , not returned after scope?)
thanks.
#include <stdio.h> #include <stdlib.h> #include <string.h> char *a() { char *str1 = "hello"; return str1; } char *b() { char *str2 = "world"; return str2; } int main() { char *main_str1 = a(); char *main_str2 = b(); puts(main_str1); puts(main_str2); return 0; }
edit: saying "hello" string takes constant place in memory , though it's inside function , can read anywhere want if have it's address (so defined malloc cant free it) - right ?
constant strings not allocated on stack. pointer allocated on stack. pointer returned a()
, b()
points literal constant part of executable memory. another question dealing topic
Comments
Post a Comment