【发布时间】:2017-12-20 13:02:21
【问题描述】:
我学会了不要让指针指向文字,因为它会导致内存泄漏。但是当我分配一个指向文字的指针时,它仍然指向与以前相同的地址:
unsigned maxlen = 20;
char* testpointer = new char[sizeof(char) * maxlen]; //Pointer points to RAM
cout << "&testpointer = " << &testpointer << endl;
strncpy(testpointer, "Happy Eastern", 13);
cout << "&testpointer = " << &testpointer << endl;
testpointer = "Merry Christmas"; // I know I shouldn't do this
cout << "&testpointer = " << &testpointer << endl;
我每次仍然得到相同的内存地址:
&testpointer = 0x28fc60
&testpointer = 0x28fc60
&testpointer = 0x28fc60
当我让指针指向文字时,地址不应该改变吗? 我认为我用 new 分配的内存应该在 RAM 中,而文字应该在 ROM 中,它应该有不同的地址。我错了吗?
谢谢你,菲利普
【问题讨论】:
-
区分指针本身的地址和指针指向的地址。再说了,你学错了。
-
使用 std::string,而不是 char 数组和 str* 函数。
标签: c++ pointers memory-leaks