C++ 动态内存错误
C++ Dynamic Memory Error
这是我的代码
int main()
{
char *something = new char[10];
something = "test";
cout << something;
delete[] something;
return 0;
}
当我调试它时,它会打开应用程序并给我一个错误 window 说 Debug Assertion Failed: _CrtlsValidHeapPointer(block)
谢谢。
something = "test";
将您的指针分配给使用静态存储分配文字分配的地址。您动态分配的原始指针丢失了。
要复制内容,请使用std::copy()
。
您需要使用 strcpy 将 "test" 复制到您的数组中。
strcpy(something, "test"); // or even better user strncpy
相反,您有:
something = "test";
关于用新地址覆盖存储在 something 变量中的指针的代码。编译器生成的字符串常量的地址。然后 delete[] 作用于这个新地址,它不指向 new.
返回的动态分配的内存
在这种情况下,something
是指向字符的指针。在第二行中,您将 something
的值更改为指向 "test" 的第一个字符,而不是您期望的值,即将 "test" 放入 [=10] 指向的内存中=].
当您 delete
试图删除 "test" 所在的内存时,它是只读内存。
一般来说,您应该考虑使用 std::string
和 C++
。如果您出于其他原因使用 char *
,请查看 strcpy
和 strncpy
这是我的代码
int main()
{
char *something = new char[10];
something = "test";
cout << something;
delete[] something;
return 0;
}
当我调试它时,它会打开应用程序并给我一个错误 window 说 Debug Assertion Failed: _CrtlsValidHeapPointer(block)
谢谢。
something = "test";
将您的指针分配给使用静态存储分配文字分配的地址。您动态分配的原始指针丢失了。
要复制内容,请使用std::copy()
。
您需要使用 strcpy 将 "test" 复制到您的数组中。
strcpy(something, "test"); // or even better user strncpy
相反,您有:
something = "test";
关于用新地址覆盖存储在 something 变量中的指针的代码。编译器生成的字符串常量的地址。然后 delete[] 作用于这个新地址,它不指向 new.
返回的动态分配的内存在这种情况下,something
是指向字符的指针。在第二行中,您将 something
的值更改为指向 "test" 的第一个字符,而不是您期望的值,即将 "test" 放入 [=10] 指向的内存中=].
当您 delete
试图删除 "test" 所在的内存时,它是只读内存。
一般来说,您应该考虑使用 std::string
和 C++
。如果您出于其他原因使用 char *
,请查看 strcpy
和 strncpy