1

Possible Duplicate:
Where are literal strings placed and why can I return pointers to them?

Suppose I have some code like the following:

char *string;

void foo(char *s)
{
   string = s;
}

foo("bar");

What is happening internally? Since I have not explicitly declared what I am passing into foo, e.g by doing something like.

char s[] = "bar";
foo(s);

will "bar" always be stored in the same memory location? Does is automatically have some memory allocated for it? If so, does this address remain the same, so that "string" always points to a char array which holds "bar"?

I suppose the more general question I am asking is: What happens internally when you pass an argument to a function without explicitly assigning it into some variable first, and then passing in that variable.

Community
  • 1
  • 1
user1209776
  • 157
  • 1
  • 3
  • 8

2 Answers2

3
char *string;

void foo(char *s)
{
   string = s;
}

foo("bar");

"bar" is a string literal. String literals have static storage duration and their lifetime (as all objects with static storage duration) is the entire execution of the program.

So basically there is a "bar" array object somewhere in your memory at the startup of your program and you are passing a pointer to its first element during the execution of your program which is totally fine.

ouah
  • 142,963
  • 15
  • 272
  • 331
2

Your code is essentially equivalent to

char *string;

string = "bar";

In this situation, assuming a sane implementation, "bar", being a string literal, will be stored in the executable at a constant location and loaded into (presumably read-only) memory, also to the same (virtual) address in memory, in order string to always point to a valid string.

  • Is there ever a circumstance where it might not be in read-only memory, and hence get overwritten? – user1209776 Oct 20 '12 at 10:07
  • 1
    @user1209776 It's implementation specific where the string literals are stored, may vary across platforms. So modifying it may work on some platforms. But it's undefined behaviour to modify it and you shouldn't rely on it. – P.P Oct 20 '12 at 10:10
  • It wouldn't be my intention to modify it. What I mean is, could the program place another variable 'over' it, when memory is required for a new variable later ? – user1209776 Oct 20 '12 at 10:15
  • @user1209776 you mean "is it possible to write `char *otherString = "foo";`" or what? –  Oct 20 '12 at 10:17
  • @user1209776 No, that's not possible. Memory is reserved for the string literal. Unless, you deliberately try to modify/overwrite it, nothing will be overwritten there. – P.P Oct 20 '12 at 10:20