@dbush的回答非常好,只是一个快速的插件,希望能让事情变得清楚。这基本上就是你正在做的事情
// In read-only memory. Just making these addresses up obviously.
// I don't know if they'd be more likely to be consecutively
// addressed or aligned in some way
0x100: "Hello World OLD"
0x200: "Hello World NEW"
现在进入您的循环
// first iteration
pchar1 = "Hello World OLD"; // ==> now pchar1 == 0x100
pchar1 = "Hello World NEW"; // ==> now pchar1 == 0x200
// second iteration
pchar1 = "Hello World OLD"; // ==> now pchar1 == 0x100
pchar1 = "Hello World NEW"; // ==> now pchar1 == 0x200
并且永远,
pchar1
只是不断被字符串文字地址覆盖。
在评论中回答您的新问题(如果我在下面):
这取决于情况。如果你有一个无限循环
分配
每次迭代的内存(使用
malloc
)或者类似的,而你从来没有
free
是的,你会有失控的内存消耗,最终耗尽:
#include <string.h>
...
// very simplified view
while(1)
{
// alloctes 50 bytes
pchar1 = malloc(50);
// doesn't have to be a random string, "Hello World NEXT"
// is still a string literal, lets say at address 0x300, but
// each time you malloc it returns a _new_ pointer to _new_
// memory. This new memory address is stored in pchar1. strcpy
// _copies_ the string literal at address 0x300 into the new
// memory pointed to by pchar1.
strcpy(pchar1, "Hello World NEXT");
// use pchar1
// ...
// WHOOPS, forgot to free. When you loop back around,
// the previous value of pchar1 will be replaced with the
// new value from malloc, but the previously allocated memory
// will still be allocated. When you lose that previous pointer/
// don't free it, that's called a memory leak. This loop will
// allocate memory indefinitely until you run out.
}
在C语言中,您必须手动管理内存,这通常意味着您必须
自由的
每次
malloc
(
but there's a debate about that depending on the situation
)
// this is fine. Not best practice, but free of leaks
// and unbound memory allocation
while(1)
{
pchar1 = malloc(50);
// use pchar1 however
free(pchar1);
}
或者,您可以完全避免动态分配内存:
while(1)
{
// here, pchar1 is allocated in _automatic storage_ (on the stack
// in every C implementation I've ever used). Here, the program
// "deallocates" pchar1 when the closing } is hit
char pchar1[50];
// the string literal is still at 0x300, we're just copying its
// data into the pchar1 memory (different address than 0x300)
strcpy(pchar1, "Hello World NEXT");
// use pchar1
// ...
// ok, as soon as we hit this closing brace } pchar1 is
// deallocated ... and reallocated new when we loop back
// around
}