Newbie char* and "string" question.

Started by
3 comments, last by wyrd 20 years, 2 months ago
Where is memory allocated for a "string" when you do the following, and when is memory for it reclaimed; char* str = "hi there"; Let me show a better example;

char* str = NULL;

void f()
{
   str = "testing testing";
}

void f2(char* str2)
{
   str = str2;
   f();
}

int main()
{
   void f2("hi");
}
 
Basically I''m pointing str to something different in various instances. When str is pointed to a new string, what happens to what it was previously pointing to?
Advertisement
In most C/C++ compiler implementations a string literal is placed in the data segment of the executable''s image. When you change the pointer in this instance, the original string stays in the same place it always was: the data segment.
Ahhh I think I understand (if memory serves me well from the Assembly days of school, heh). So when I compile my app, it simply places the string literals in the data segment, and references them from there? That means they're statically allocated memory and will be reclaimed when the program ends?

Curious though, when not using pointers and using an array instead, they seem to be allocated on the stack (where the array is pointing to). Which means their memory is reclaimed after local scope is gone;

char* str = NULL;f(){   char stmp[] = "hi there";   str = stmp;}int main(){   f();}  


In this case, str is going to point to undefined memory after the function ends. Or at least, in my experience it has.

Perhaps there's something of a simplistic nature that I'm still not getting.

[edited by - wyrd on January 22, 2004 1:33:48 PM]
In that code fragment, the compiler will most likely embed "hi there" in the data segment. When f() is called, it copies the "hi there" from the data segment to the stack in stmp[]. You assign that stack address to str, which then goes out of scope and dies a horrible death, leaving str with a bad pointer. However, "hi there" is still in the data segment.

It might help if you tried compiling the code yourself into assembly. It's the /FA switch for MSVC. -S for gcc (IIRC).

edit: bad bad grammar

[edited by - SiCrane on January 22, 2004 1:43:03 PM]
Hmm, interesting. I''ll give it a shot, thanks.

This topic is closed to new replies.

Advertisement