void aFunction_2()
{
char* c = new char[10];
c = "abcefgh";
}
问题:
将
c = "abdefgh"
存储在new char[10]
中吗?如果
c = "abcdefgh"
是另一个内存区域,我应该释放它吗?如果我想要将信息保存到
char[10]
中,我应该使用像strcpy
这样的函数将信息放入char[10]
中吗?
void aFunction_2()
{
char* c = new char[10];
c = "abcefgh";
}
问题:
将 c = "abdefgh"
存储在 new char[10]
中吗?
如果 c = "abcdefgh"
是另一个内存区域,我应该释放它吗?
如果我想要将信息保存到 char[10]
中,我应该使用像 strcpy
这样的函数将信息放入 char[10]
中吗?
是的,那是内存泄漏。
是的,您可以使用strcpy将字符串放入分配的char数组中。
由于这是C++代码,您都不需要使用。您应该使用std::string。
void aFunction_2()
{
char* c = new char[10]; //OK
c = "abcefgh"; //Error, use strcpy or preferably use std::string
}
1- c = "abdefgh"会被分配到新的char[10]内吗?
不会,您正在将指针从先前指向的10个字节的内存位置更改为指向新的常量字符串,导致十个字节的内存泄漏。
2- 如果c = "abcdefgh"是另一个内存区域,我应该释放它吗?
不需要,它没有在堆上分配,而是在只读内存中。
3- 如果我想要保存信息到char[10]中,我需要使用像strcpy这样的函数来将信息放入char[10]中吗?
我不确定您在这里所说的“inner”是什么意思。当您使用new进行分配时,内存在堆中分配,在正常情况下可以从程序的任何部分访问内存块,如果提供了内存块的指针。
new
的内容通常会导致崩溃;以及strcpy
可以完成任务...但在C++中通常不使用。由于没有人用代码回答,std::uninitialized_copy_n
(或者只是std::copy_n
,这里真的没有区别)比strcpy
更符合C++:
#include <memory>
static char const abcs[] = "abcdefgh"; // define string (static in local scope)
char *c = new char[10]; // allocate
std::copy_n( abcs, sizeof abcs, c ); // initialize (no need for strlen)
// when you're done with c:
delete[] c; // don't forget []
std::string
代替:#include <string>
std::string c( "abcdefgh" ); // does allocate and copy for you
// no need for delete when finished, that is automatic too!
delete[]
对它们进行释放。这里的[]
很重要。使用 new x[]
分配的内存都必须使用 delete[]
进行释放。无论是编译器还是运行时都不会在你使用普通的 delete
时发出警告,因此记住这个规则非常重要。
std :: string
。 - sbi