以下是3个功能.main()按预期打印出来.现在,在mycharstack()中,字符串存储在堆栈中我猜,因为"ch"超出范围,它应该不能返回字符串.它是如何正常工作的?我想存储在mychar()中的字符串也在堆栈上.它应该正常工作吗?我猜在代码和内存泄漏中还有其他错误,如果有的话请告诉我.我可以使用std :: string更清洁,更轻松.但我想了解char*发生了什么.
#include <iostream>
using namespace std;
char* mychar()
{
return "Hello";
}
char* mycharstack()
{
char* ch = "Hello Stack";
return ch;
}
char* mycharheap()
{
char* ch = new char;
ch = "Hello Heap";
return ch;
}
int main()
{
cout << "mychar() = " << mychar() << endl;
cout << "mycharstack() = " << mycharstack() << endl;
cout << "mycharheap() = " << mycharheap() << endl;
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
not*_*row 17
在C++中,字符串处理不同于例如pascal.
char* mycharheap()
{
char* ch = new char;
ch = "Hello Heap";
return ch;
}
Run Code Online (Sandbox Code Playgroud)
这样做如下:
char* ch = new char; 为一个字符创建内存,并将其分配给变量 chch = "Hello Heap";分配给ch只读内存的变量指针,其中包含字节"Hello Heap\0".此外,变量的原始内容ch丢失,导致内存泄漏.return ch;返回存储到变量的指针ch.你可能想要的是什么
char* mycharheap()
{
char* ch = new char[11] /* 11 = len of Hello Heap + 1 char for \0*/;
strcpy(ch, "Hello Heap");
return ch;
}
Run Code Online (Sandbox Code Playgroud)
注意strcpy- >你有内存ch,有11个字符的空间,你用字符串从内存的只读部分填充它.
在这种情况下会有泄漏.写完后你需要删除内存,如:
char* tempFromHeap = mycharheap();
cout << "mycharheap() = " << tempFromHeap << endl;
delete[] tempFromHeap;
Run Code Online (Sandbox Code Playgroud)
但是,我强烈建议不要这样做(在被调用者中分配内存并在调用者中删除).对于这种情况,例如有STL std::string,另一种常见且更合理的方法是在调用者中分配,传递给被调用者,用结果"填充"内存,并再次在调用者中释放.
导致未定义行为的原因如下:
char* mycharstack()
{
char[] ch = "Hello Heap"; /* this is a shortcut for char[11] ch; ch[0] = 'H', ch[1] = 'e', ...... */
return ch;
}
Run Code Online (Sandbox Code Playgroud)
这将在堆栈上创建带有字节的数组"Hello Heap\0",然后尝试返回指向该数组的第一个字节的指针(可以在调用函数中指向任何内容)
| 归档时间: |
|
| 查看次数: |
61682 次 |
| 最近记录: |