Firstly, I give two code fragments of a C/C++ function that reveal different strategies that C/C++ manage memory allocation. I was been asked these questions in a job interview.:(
#1
char *func()
{
char *p = "hello world";
return p;
}
#2
char *func()
{
char p[] = "hello world";
return p;
}
Can people still get the string "hello world" when the func returns?
This answer is YES and NO respectively.
Because in #1, "hello world" is a string constant. And in #2, the storage place of "hello world" is STACK. But when writing in this way, static char p[] = "hello world";
, the answer will be YES.
So, my question is that How C/C++ govern memory allocation of a function?
Recalling what my interviewer told me. I can remember something like, STACK/HEAP/DATA SEGMENT/PROGRAM SEGMENT/*. I wish that anyone can describe this accurately.
Thanks.
CONTENTS ADDED
"Knowing how your codes are managed in memory will help programmers write their code." This is what the interviewer said to me.
The examples given above are used to describe this. What I want to ask is that How are memory segments organized from the point of view of program. Answers that I expect may like
|___________________|
| STACK |
|___________________|
| HEAP |
|___________________|
| DATA SEGMENT |
|___________________|
| PROGRAM SEGMENT |
|___________________|
| ... |
| |
From the point view of a program, I am not sure whether memory partition like this is correct. (And also, other segments that store specific kind of data may exist.)