Jake
Jake

Reputation: 16837

C character array initialization

In the following code:

char *p = "Linux";

Is the memory for "Linux" on the stack or the read only segment of the program?

Refer to question 9 in the article 12 Interesting C Interview Questions and Answers.

Thanks.

Upvotes: 1

Views: 226

Answers (2)

David Schwartz
David Schwartz

Reputation: 182743

The implementation is free to store it wherever it wants. It's a constant, so it can be in read-only memory, but it is not required to be.

My instructor for C programming always says its on the stack, hence the doubt.

He probably means the pointer. Consider:

char *p = "Linux";
p = "Rules";

In the second line, something changed from pointing to "Linux" to pointing to "Rules". That thing that just changed is on the stack.

Upvotes: 3

chacham15
chacham15

Reputation: 14251

As the link says, it is not stored in dynamically allocated memory, rather the memory that is where the code itself lives. I.e. the read only sections. Hence the reason why trying to change it results in a segfault.

Upvotes: 0

Related Questions