c - Do i must malloc a returned string inside a function? -


this question has answer here:

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

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -