Aayush Sharma Aayush Sharma - 27 days ago 164
C Question

When is the address of a string allocated?

int main()
char str[10];
printf("The address of string is %x", str);

Every time I run the program, the same memory address shows up. Why is that so?
When does the memory get allotted?

Answer Source

As your str has function scope and no storage class specifier, it has automatic storage duration by default. This means it exists as long as the execution doesn't leave its scope (the main() function). So the answer to your question is: The implementation must reserve memory for this variable whenever main() is entered. But the implementation would still be free to do it earlier, because this wouldn't lead to different observable behavior.

As for your other question, there's nothing in the specification of C telling you anything about addresses. Most likely, your implementation uses a call stack to store local (automatic) variables and in your system, this call stack is always located at the same virtual address. But this is guessing, an implementation can do whatever it likes.