3
struct Example
{
     char* string;
     int x;
};

When I allocate a new instance of Example 8 bytes are allocated (assuming that sizeof(char*)=4). So when I call this:

Example* sp = new Example();
sp->string = "some text";

How is the string allocated? Is is placed in a random empty memory location? or is there some kind of relation between sp and member string?

So, "some text" makes a dynamic memory allocation?

Tiago Costa
  • 4,151
  • 12
  • 36
  • 54
  • @Roee Gavirel: It does not look to me like he uses any string class. – Nobody moving away from SE Sep 11 '11 at 14:04
  • No, it is not making a dynamic memory allocation. You may find this related question helpful: http://stackoverflow.com/questions/4970823/where-in-memory-are-string-literals-stack-heap – aroth Sep 11 '11 at 14:06
  • Does anybody get the feeling that Gavriel might not know what s/he is talking about? No offense. – Patrick87 Sep 11 '11 at 14:08
  • In this example, you really should have `const char*`. The code as written is using a deprecated conversion from `const char[10]` to `char*`, discarding a `const` on the way. – MSalters Sep 12 '11 at 09:01

4 Answers4

6

String literals like that are put wherever the compiler wants to put them, they have a static storage duration (they last for the life of the entire program), and they never move around in memory.

The compiler usually stores them in the executable file itself in a read-only portion of memory, so when you do something = "some text"; it just makes something point to that location in memory.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
3

The string is in the executable when you compile it.

sp->string = "some text";

This line is just setting the pointer in the struct to that string. (note: you have a double typo there, it's sp, and it's a pointer so you need ->)

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
1

In this case, the constant string value should be put into the program's data area, and the pointer in your struct will point to that area rather unambiguously as long as it has the value. In your words, it is placed into a random area of memory (in that it is unrelated to where your struct instance goes).

Patrick87
  • 27,682
  • 3
  • 38
  • 73
1

this way you made a string "CONSTANT" first, it stays in the program's heap (but not stack), You needn't manage it (alloc the memory of free it), and it can not be dynamically freed indeed.

shiying yu
  • 93
  • 7