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?

4
  • @Roee Gavirel: It does not look to me like he uses any string class. Commented Sep 11, 2011 at 14:04
  • No, it is not making a dynamic memory allocation. You may find this related question helpful: stackoverflow.com/questions/4970823/… Commented Sep 11, 2011 at 14:06
  • Does anybody get the feeling that Gavriel might not know what s/he is talking about? No offense. Commented Sep 11, 2011 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. Commented Sep 12, 2011 at 9:01

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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 ->)

Comments

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).

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.