The following program will print on the screen "Hello\nWorld\n" ('\n' = line down) as it supposed to. But actually, as i learned, something here isn't done as it should be. The "hello" and "world" strings are defined inside a function (and therefore are local and their memory is released at the end of the function's scope - right?). Actually we don't do a malloc for them as we are supposed to (to save the memory after the scope). So when a() is done, isn't the memory stack move up it's cursor and "world" will be placed in the memory at the same place where "hello" was ? (it looks like it doesn't happen here and I don't understand why, and therefore, why do i usually need to do this malloc if actually the memory block is saved and not returned after the 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: So what you are saying actually is that my "hello" string takes a constant place in memory and even though it's inside a function , i can read it from anywhere i want if i have it's address (so its defined just like a malloc but you cant free it) - right ?