开发者

Strings in memory

struc开发者_开发百科t 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?


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.


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜